I've searched a lot, but can't find the answer to this rather simple question:
In Symfony 2.8 I have a form, that renders a country field. Based on it's selection I want to display a zipcode and federalstate field only for the choice 'Deutschland' (data 'D'). Here is the code for the country-field:
->add('nationveranstaltungsort', ChoiceType::class, array(
'choices' => array(
'D' => 'Deutschland',
'AFG' => 'Afghanistan',
//many other countries following
),
'data' => 'D',
'label' => 'Nation Tagungsstätte'))
it's prepopulated with the Choice 'Deutschland', data 'D'.
based on that i want to dynamically display:
->add('plzveranstaltungsort', TextType::class, array('label' => 'PLZ', 'attr' => array('size' => '5', 'maxlength' => '5')))
->add('bundeslandveranstaltungsort', ChoiceType::class, array(
'choices' => array(
0 => ' ',
1 => 'Baden-Württemberg',
2 => 'Bayern',
3 => 'Berlin',
4 => 'Brandenburg',
5 => 'Bremen',
6 => 'Hamburg',
7 => 'Hessen',
8 => 'Mecklenburg-Vorpommern',
10 => 'Nordrhein-Westfalen',
11 => 'Rheinland-Pfalz',
12 => 'Saarland',
13 => 'Sachsen',
14 => 'Sachsen-Anhalt',
15 => 'Schleswig-Holstein',
16 => 'Thüringen',
),
'data' => 0,
'label' => 'Bundesland Tagungsstätte'))
If "Deutschland" is not selected, I simply want to hide/disable these fields (and handle the null value somewhere else).
I tried http://symfony.com/doc/current/form/dynamic_form_modification.html and some other javascript stuff, but as I basically don't know any JS, I couldn't find any proper resources.
Since by default the nationveranstaltungsort field has Germany selected, then there is no need to hide plzveranstaltungsort. You can hide in Javascript by using something like:
var bund = document.getElementById("bundeslandveranstaltungsort");
bund.style.display = "none";
Then to show the element use:
bund.style.display = "inline";
Depending on what css you are using, you might need to use:
bund.style.display = "block";
In you form you can specify an attribute to run a Javascript function on change like so:
->add('nationveranstaltungsort', ChoiceType::class, array(
'choices' => array(
'D' => 'Deutschland',
'AFG' => 'Afghanistan',
),
'data' => 'D',
'label' => 'Nation Tagungsstätte',
'attr' => array(
'onchange' => 'changeCountry()',
),
))
Then in the Javascript function changeCountry() hide the element or show it using the above.
The ids I show are not actually what you will use, but if you use the browser tools, for example in Firefox (I suggest using FireFox for testing), you can right-click on the choice element and choose "Inspect element"; then you can see what the "actual" id value is that you need to use. It depends on your Form name.
Related
I have a dropdown with countries, and I want to add a dependent dropdown or textfield with Ajax according to the selected value in the main dropdown.
Case 1
For example, if the user selects the United States(US) or Canada(CA), the Ajax should fire and add a dependent dropdown.
If the US
Dropdown
New York
New Jersey
California
And more options
If CA
Dropdown
Ontario
Manitoba
Quebec
And more options
The select(dependent dropdown) has to be required.
Case 2
If the user selects any other country, the Ajax should fire and add a dependent textfield
If any country but not US nor CA
Textfield
The textfield has to be required too.
I tried the options here
Using the AJAX command option
//This is my main select
$form['country'] = [
'#type' => 'select',
'#title' => $this->t(‘Select Country'),
'#options' => [
‘US’ => t(‘United State’),
'CA' => t('Canada’),
‘BR’ => t(‘Brazil’),
‘CO’ => t(‘Colombia’),
],
'#default_value' => 'US',
'#required' => TRUE,
'#empty_option' => $this->t('Please select'),
'#ajax' => [
'callback' => [$this, 'addDependentField’],
'event' => 'change',
'wrapper' => 'output-dependent’, // This element is updated with this AJAX callback.
'progress' => [
'type' => 'throbber',
'message' => $this->t('Verifying entry...'),
],
]
];
// Here I want to add a select or textfield. This dependes on the value from the main select above
$form[‘dependent_field’] = [
'#title' => $this->t('State/Province'),
'#prefix' => '<div id=“dependent-field”>’,
'#suffix' => '</div>',
];
public function addDependentField(array &$form, FormStateInterface $form_state) {
$selectedValue = $form_state->getValue('country');
switch ($selectedValue) {
case 'US':
$elem = [
'#type' => 'select',
'#options' => [
'NY' => t('New York'),
'CA' => t('California'),
'NJ' => t('New Jersey'),
'WA' => t('Washington'),
],
'#required' => TRUE,
'#attributes' => [
'id' => ['edit-output'],
],
];
break;
case 'CA':
$elem = [
'#type' => 'select',
'#options' => [
'ON' => t('Ontario'),
'PE' => t('Prince Edward Island'),
'QC' => t('Quebec'),
],
'#required' => TRUE,
'#attributes' => [
'id' => ['edit-output'],
],
];
break;
default:
$elem = [
'#type' => 'textfield',
'#size' => '60',
'#required' => TRUE,
'#attributes' => [
'id' => ['edit-output'],
],
];
break;
}
$renderer = \Drupal::service('renderer');
$renderedField = $renderer->render($elem);
// Create the AjaxResponse.
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#edit-output-2', $renderedField));
// Return the AjaxResponse object.
return $response;
}
This works only the first time, then stops working, I think it is because the fields’ types are different.
Using the render array option
I just changed all code after switch for the code below
return $form['dependent_field'] = $elem;
And it has the same behavior, it works only the first time then stops working.
I also tried
This to update multiple times
Replace more than one element form
Drupal 8 add ajax form element after ajax call
And also I found the same bad behavior after trying those answers, I still think it might be because one field is dropdown, and the other is `texfield`` because I want to update it over the same field with different types.
I think you don't need a specific AJAX for it.
You can use Form API '#states'
You can use this code to do ajax request.
This will get the list of states for the country selected
$('#countries').change(function(){
$.get("url/"+country,function(data,status){
various countries = JSON.parse(data);
for(var i = 0; i<countries.length; i++){
document.getElementById().innerHTML += "<option>"+countries[i].state+"</option>";
//here you can add the form field you wish to.
}
}
});
I'm developing a prestashop module.in my controller renderForm i have drop down list to load week days.but it showing only first letter of the day.
public function renderForm() {
$days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
'input' => [
[
'type' => 'select',
'lang' => true,
'required' => true,
'label' => $this->l('WeekDay'),
'name' => 'weekday',
'options' => [
'query' => $days,
],
],
]
}
Showing like this
Inspect Element
Your query value should be like below format as per prestashop 1.7 documentation.
$days = array(
array(
'id' => 1, // The value of the 'value' attribute of the <option> tag.
'name' => $this->trans('Monday', array(), 'Admin.International.Feature') // The value of the text content of the <option> tag.
),
array(
'id' => 2,
'name' => $this->trans('Tuesday', array(), 'Admin.International.Feature')
),
);
I use the yii2 kartik switch input with the type radio and i want to get the value of the selected option in javascript (specially in a JsExpression), here is my code :
$model->orientation = 'Portrait';
echo $form->field($model, 'orientation')->widget(SwitchInput::classname(), [
'name' => 'information_orientation',
'type' => SwitchInput::RADIO,
'value' => 'Portrait',
'items' => [
['label' => 'Portrait   ', 'value' => 'Portrait'],
['label' => 'Paysage   ', 'value' => 'Paysage'],
],
'pluginOptions' => [
'onText' => 'Oui',
'offText' => 'Non',
'onColor' => 'success',
'offColor' => 'danger',
'size' => 'mini'
],
'labelOptions' => ['style' => 'font-size: 13px'],
]);
I have tried :
$([name='information-orientation']).val()
But it returned an undifined value
SwitchInput class does not care about the name property you give it
according to their docs, you need to wrap name in a options array
echo $form->field($model, 'orientation')
->widget(SwitchInput::classname(), [
'options' => ['name' => 'information_orientation'],
'type' => SwitchInput::RADIO,
....
from docs:
options: array the HTML attributes for the widget input tag.
edit:
you can then use the following
// to get value:
$("[name='information_orientation']").val()
// to check if the switch is or on off
$("[name='information_orientation']").prop('checked')
I'm using Laravel 4. I'm having some problem. I have a users table with fields like. State, Region, Area and City, they are all in string (varchar).
Now, I have my "Edit Users" page. In edit users how can I display the users info ing State, Region etc. in a Select Dropdown? Here's my code.
{{ Form::select('state', array(
'' => 'Choose One', 1 => 'Luzon', 2 => 'Visayas', 3 => 'Mindanao'),
null,
array('class' => 'selectpicker',
'id' => 'state',
'data-live-search' => 'true',
'onchange' => 'document.getElementById("state2").value=this.options[this.selectedIndex].text'
));
}}
How can I make a value for that specific user already appeared or selected in the dropdown?
Thanks!
See if this works for you:
$states = array( 'Choose One', 'Luzon', 'Visayas', 'Mindanao' );
{{ Form::select('state',
$states,
array_search($user->State, $states ), // default value
array(
'class' => 'selectpicker',
'id' => 'state',
'data-live-search' => 'true',
'onchange' => 'document.getElementById("state2").value=this.options[this.selectedIndex].text'
));
}}
I am trying to get the IDs of all the selected check boxes in yii using JAVASCRIPT. Now i am able to get only the first element ID. Can anyone please suggest the correct code to get all the check box ID.
My View:
<input type="button" value="Multiple Host Date Entries" onclick="act();" />
<div id="grid"></div>
<?php
//zii.widgets.grid.CGridView bootstrap.widgets.TbExtendedGridView
$obj=$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'host_grid',
'dataProvider'=>$dataProvider,
'type' => 'striped bordered',
//'filter' => $model,
//'type' => 'striped bordered condensed',
//'summaryText' => false,
////'afterAjaxUpdate'=>'\'changeTRColor()\'',
//'itemView'=>'_view',
'columns'=>array(
array(
'id' => 'selectedIds',
'class' => 'CCheckBoxColumn',
'selectableRows'=>2,
'value' => '$data->host_id',
'checkBoxHtmlOptions' => array('name' => 'idList[]'),
),
array( // display 'create_time' using an expression
'name'=>'host_name',
'value'=>'$data->host_name',
),
array(
'name'=>'host_serviceid',
'value'=>'$data->host_serviceid',
),
array(
'name'=>'status',
'value'=>'$data->status',
),
array(
'class'=>'CButtonColumn',
'template'=>'{edit_date}{update}{delete}',
'htmlOptions'=>array('width'=>'95px'),
'buttons' => array(
'update'=> array(
'label' => 'Update',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/a.png',
),
'delete'=> array(
'label' => 'Delete',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/d.png',
),
'edit_date' => array( //the name {reply} must be same
'label' => 'Add Date', // text label of the button
'url' => 'Yii::app()->createAbsoluteUrl("NimsoftHostsDetails/View", array("id"=>$data->host_id))', //Your URL According to your wish
'imageUrl' => Yii::app()->baseUrl.'/images/icons/m.png', // image URL of the button. If not set or false, a text link is used, The image must be 16X16 pixels
),
),)
),
))
;
?>
I must select some check boxes and click on multiple host date entries button to go to the specific controller.
My JavaScript:
function act()
{
var idList=$("input[type=checkbox]:checked").serializeArray();
var jsonStr = JSON.stringify(idList);
/* Object.keys(idList).forEach(function(key) {
console.log(key, idList[key]);
alert(idList[key]);
});*/
var a=$("input[type=checkbox]:checked").val();
alert(a);
if(idList!="")
{
if(confirm("Add Dates for multiple hosts?"))
{
var url='<?php echo $this->createUrl('Nimsoft/Date_all',array('idList'=>'val_idList')); ?>';
url=url.replace('val_idList',jsonStr);
//url=url.replace('val_idList',json_encode(idList));
//alert(url);
window.open(url);
/*$.post('Date_all',idList,function(response)
{
$.fn.yiiGridView.update("host_grid");
});*/
}
}
else
{
alert("Please Select atleast one host");
}
}
I need to pass the IDs to NIMSOFT controller so that I can have a for loop to process each one of those.
you can retrieve the checked column in client side (javasctipt):
var idArray = $(gridID).yiiGridView('getChecked', columnID);
// or
$.fn.yiiGridView.getSelection(gridID);
For all checked row ids we use this
var id = $.fn.yiiGridView.getChecked("your-grid-id", "selectedIds"); // array of seleted id's from grid