I have data about citizen's country and city. And these data are displayed in a drop down list using js. When I try to update them, the drop down list doesn't show the data before the save. How to solve it.
My code is:
<?= $form->field($organization, 'country_id')->dropDownList([],[
'prompt' => '---',
'onchange' => '
$.get("../citizeninfo/city?id='.'"+$(this).val(), function(data){
$("select#training-city_id").html(data);
});'
]) ?>
<?= $form->field($organization, 'city_id')->dropDownList([], ['prompt' => '---']) ?>
You can use this way :
City model
public static function getCityByCountry($countryId)
{
$cities = self::find()
->where(['country_id' => $countryId])
->select(['name'])
->indexBy('id')
->orderBy(['name' => SORT_ASC])
->column();
return $cities;
}
Form.php
<?= $form->field($organization, 'city_id')->dropDownList(City::getCityByCountry($organization->country_id), ['prompt' => '---']) ?>
Do the same for country_id.
You can call same function in your jquery also to get city of selected country.
Set Vaue:
<?= $form->field($model, 'sex')->dropDownList(
['0' => 'Male',
'1' => 'Female']
) ?>
Related
So what I want to do is populate a dropdown in Yii framework with ajax using my database values in drop down. I using Kartik widget in it here is my dropdown code,
<?php $primaryfield = [1 => 'Business Development(Sales)', 2 => 'Graphic Design', 3 => 'Social Media Marketing', 4 => 'Web Development']; ?>
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), ['data' => $primaryfield,
'options' => ['placeholder' => 'Enter Your Primary Field', 'multiple' => false], 'pluginOptions' => ['tags' => false, 'tokenSeprators' => [',', ' '], 'maximumInputLength' => 20],])->label(false); ?>
I know everything about Ajax in PHP but don't know how to use it in Yii framework using Kartik widget I have all the primary fields value in my database but unfortunately, I am only able to display them in static basis not dynamic basis using ajax
If I get you clear, you want to have a drop-down list in which their items are dynamically generated by your database.
This is the way you can achieve with kartik dropdown widget.
I'll first create active form field which contains predefined categories as follows
<?php $form = ActiveForm::begin();
//Initialize predefined categories
$data = [
'1' => 'Business Development(Sales)',
'2' => 'Graphic Design',
'3' => 'Social Media Marketing',
'4' => 'Web Development',
];
?>
These field will prompt database to retrieve items for particular category via AJAX
<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), [
'data' => $data,
'options' => ['placeholder' => 'Enter your primary field'],
'pluginOptions' => [
//'allowClear' => true
],
'pluginEvents' => [
"change" => "function() {
var id = $(this).val(); //extract the id of selected category
$.ajax({
method : 'GET',
dataType : 'text',
url : '../yourcontroller/populate?id=' + id,
success : function (response) {
var response = JSON.parse(response);
var myDropDownList = document.getElementById(\"model-item\");
$.each(response, function(index, value) {
var option = document.createElement(\"option\");
option.text = value;
option.value = index;
try {
myDropDownList.options.add(option);
}
catch (e) {
alert(e);
}
});
}
});
}",
],
]);
?>
<?= $form->field($model,'item')->dropdownList(
['prompt'=>'Select Item']
);
?>
Now create action in your controller that will query items from your database based on the category selected and return it to the Item field via ajax.
<?php
public function actionPopulate($id)
{
// the id above is the one selected from the category field so you can use
// that Id now to retrieve items from your item-field with ajax
/* in you case */
$results = Category::find()
->select('items')
->where(['id' => $id])
->asArray()
->all();
//these hard-coded values are for the demonstration
$results = [
'1'=>'maziwa',
'2'=>'ugali',
'3'=>'samaki',
'4'=>'kuku',
'5'=>'mtetea',
];
return json_encode($results);
}
?>
Hope this helps!
i have the below form field of dropdown list.My problem is default option selected is not happening.The option value is coming as POST request.
$_REQUEST['id']=8;
<?= $form->field($model, 'id')->dropDownList(ArrayHelper::map($model,'id','name'),
[
isset($_REQUEST['id'])?'"options"=>[$_REQUEST["id"]=>["selected"=>true]]':'',
'prompt' => 'Select ',
'onChange' => '$.get("'.Yii::$app->urlManager->createUrl('data/datalist?id=').'"+$(this).val(),function(data){$("#dashboard-id").html(data);})',
])
?>
you have done the mistake in options.Try like below:
<?= $form->field($model, 'id')->dropDownList(ArrayHelper::map($model,'id','name'),
[
'options'=>isset($_REQUEST['id'])?[$_REQUEST["id"]=>["selected"=>true]]:'',
'prompt' => 'Select ',
'onChange' => '$.get("'.Yii::$app->urlManager->createUrl('data/datalist?id=').'"+$(this).val(),function(data){$("#dashboard-id").html(data);})',
])
?>
So, I want to have two radio button in separate place, I have been trying to search for the solution and everyone suggests to use radiolist which is not possible in my case.
If I put it like this (work_part_time button) : (below)
<div class="row">
<div class="col-sm-2">
<?= $form->field($model, 'work_part_time')->radio(['label' => 'yes', 'value' => 1])?>
</div>-
<div class="col-sm-3">
<?= $form->field($model, 'hour_week')->textInput(['type' => 'number', 'placeholder' => 'Hour/Week'])->label(false)?>
</div>
<div class="col-sm-3">
<?= $form->field($model, 'part_time_rate')->textInput(['type' => 'number', 'placeholder' => 'rate/hour(SGD)'])->label(false)?>
</div>
</div>
<div class="form-group">
<?= $form->field($model, 'work_part_time')->radio( [0 => 'No'])->label('No')?>
</div>
<hr>
<div class="row">
<div class="col-sm-2">
<?= $form->field($model, 'work_part_time')->radio(['label' => 'yes', 'value' => 1])?>
</div>-
<div class="col-sm-3">
<?= $form->field($model, 'hour_week')->textInput(['type' => 'number', 'placeholder' => 'Hour/Week'])->label(false)?>
</div>
<div class="col-sm-3">
<?= $form->field($model, 'part_time_rate')->textInput(['type' => 'number', 'placeholder' => 'rate/hour(SGD)'])->label(false)?>
</div>
</div>
<div class="form-group">
<?= $form->field($model, 'work_part_time')->radio( [0 => 'No'])->label('No')?>
</div>
<hr>
I only can get 0 for the value.
Anyone has found the solution for this?
Yii will assign a checked or unchecked value to the radio button depending on the value of the stored attribute, so if the value is 0 it will check the button that has the value 0. Your problem seems to have been the hidden input that Yii automatically generates. As others have suggested, you need to set this to null if you want more than one radio button for the same field.
If the user checks another button, then all other radio buttons with the same name will become unchecked. The name of the attribute is generated automatically by Yii when it creates the button.
Try these for your radio buttons:
<?= $form->field($model, 'work_part_time')->radio(['label' => 'Option 1', 'value' => 1, 'uncheck' => null]) ?>
<?= $form->field($model, 'work_part_time')->radio(['label' => 'Option 2', 'value' => 0, 'uncheck' => null]) ?>
<?= $form->field($model, 'work_part_time')->radio(['label' => 'Option 3', 'value' => 2, 'uncheck' => null]) ?>
<?= $form->field($model, 'work_part_time')->radio(['label' => 'Option4', 'value' => 3, 'uncheck' => null]) ?>
Each button needs a different value, and this is the value that will be stored in your field when the record is saved.
There can only ever be one button checked, so if you have multiple buttons with the same value, and the same name, as you seem to have in your examples, then only the last one in the set will be checked. I don't know of a way round this. I suggest you use <formgroup> to split up your form into logical sections, each section relating to whether work_part_time is yes or no. You seem to have started doing this!
I've personally checked your code in my system. This code returning 0 or 1 (in respective of selection of radio button.) It's working Fine. You can use my code.
In below code, if you want to give label as Work part time or some other, put in ->label('Work Part Time');
.
. // Your code
<?= $form->field($model, 'work_part_time')->radioList([1 => 'yes', 0 => 'No'])->label('Work Part Time'); ?>
.
. // Your code
AND
1) If you want to check 'Yes' as default checked radio button, then you have to assign like this <?php $model->status_id = 1?>
.
. // Your code
<?php $model->status_id = 1?>
<?= $form->field($model, 'work_part_time')->radioList([1 => 'yes', 0 => 'No'])->label('Work Part Time'); ?>
.
. // Your code
2) If you want to check 'No' as default checked radio button, then you have to assign like this <?php $model->status_id = 0?>
.
. // Your code
<?php $model->status_id = 0?>
<?= $form->field($model, 'work_part_time')->radioList([1 => 'yes', 0 => 'No'])->label('Work Part Time'); ?>
.
.//Your code
try this:
<?php echo $form->radioButton($model,'user_work_part_time',array('value'=>1,'uncheckValue'=>null));
$form->radioButton($model,'user_work_part_time',array('value'=>0,'uncheckValue'=>null));
?>
add 'uncheckValue'=>null in htmlOption array it will work.
If you substitute "uncheck" with "uncheckValue", the voted answer will work, except it will only post the value of the last radio on the list if selected and 0 for the rest. To make it work and post selected values as intended, I added some JS code to it. Hope it will help someone down the road.
<!-- Complete solution for Radio buttons on separate places Yii2 together with its JS function-->
<php use yii\web\View; ?>
<?= $form->field($model, 'work_part_time')->radio(['label' => 'Option 1', 'value' => 1, 'uncheckValue' => null,'onChange'=>' if($(this).prop("checked")){ var radioValue = 1;$(this).val(radioValue); var radioName = "Model[work_part_time]"; RadioSelected(radioName,radioValue);}else{$(this).val("")};']) ?>
<?= $form->field($model, 'work_part_time')->radio(['label' => 'Option 2', 'value' => 0, 'uncheckValue' => null,'onChange'=>' if($(this).prop("checked")){ var radioValue = 0; $(this).val(radioValue); var radioName = "Model[work_part_time]"; RadioSelected(radioName,radioValue);}else{$(this).val("")};']) ?>
<?= $form->field($model, 'work_part_time')->radio(['label' => 'Option 3', 'value' => 2, 'uncheckValue' => null,'onChange'=>' if($(this).prop("checked")){ var radioValue = 2; $(this).val(radioValue); var radioName = "Model[work_part_time]"; RadioSelected(radioName,radioValue);}else{$(this).val("")};']) ?>
<?= $form->field($model, 'work_part_time')->radio(['label' => 'Option4', 'value' => 3, 'uncheckValue' => null,'onChange'=>' if($(this).prop("checked")){var radioValue = 3; $(this).val(radioValue); var radioName = "Model[work_part_time]"; RadioSelected(radioName,radioValue);}else{$(this).val("")};']) ?>
<?php
//JS Function
$RadioONSeparatePlaceJS = <<<JS
function RadioSelected(radioName,radioValue)
{
$('input[name="' + radioName + '"]').val(radioValue);
}
JS;
$this->registerJs($RadioONSeparatePlaceJS,View::POS_HEAD);
?>
Thank you for the great answer Joe Miller.
I want the radio button preselected in my form.
<?= $form->field($model, 'config')->radioList(['1'=>'Automatic Entry',2=>'Manual Entry'])
->label('Barcode/Book No Generation'); ?>
The preselected values are taken from $model->config. That means that you should set that attribute to the value that you want preselected :
$model->config = '1';
$form->field($model, 'config')->radioList([
'1' => 'Automatic Entry',
'2' => 'Manual Entry',
]);
The relevant doc for this is in the ActiveForm class.
if you want to use default value of radio, you can use following codes:
<?php $model->isNewRecord==1 ? $model->config=1:$model->config;?>
<?= $form->field($model, 'config')->radioList(
[
'1'=>'Automatic Entry',
'2'=>'Manual Entry'
])->label('Barcode/Book No Generation');
?>
You have to set 'config' attribute.
$model->config = 1;
You'll have first radio button selected when form is loaded.
tarleb is right.
Long shot in the dark since I'm not awfully familiar with yii2, but based on the documentation you should be able to do something like this.
$form->field($model, 'config')->radioList([
'1'=>'Automatic Entry',
'2'=>'Manual Entry',
], [
'item' => function ($index, $label, $name, $checked, $value) {
return Html::radio($name, $checked, ['value' => $value]);
},
]);
// [...]
ActiveForm::end();
I have a dropdownlist in my _form model and I want to add a empty value (which I want as default). I have the following:
In _form:
<?php echo $form->labelEx($model,'country_id'); ?>
<?php echo $form->dropDownList($model,'country_id',Country::items(),array('empty' => '--Select a country--')); ?>
<?php echo $form->error($model,'country_id'); ?>
In Model Country:
public static function items()
{
return CHtml::listData(Country::model()->findAllBySql(
'SELECT * from country'),
'id', 'name');
}
Even my empty option is in the first row in dropdownlist, the 1st country in list shows as default.
I tried:
<?php echo $form->dropDownList($model,'country_id',
Country::items(),array('empty'=>'--Select a country--',
'options'=>
array(
'3'=>array('selected'=>'selected')
)
));
?>
In this way I can choose the default option, but cant set it to empty value, just countries that came from model:items.
Any idea?
Are you sure that country_id property of your model is not set to anything when you print the dropdown list? The following works for me if $model instance is created using new Country() operator but not by populating properties from database:
<?php echo $form->dropDownList(
$model,
'country_id',
Country::items(),
array(
'empty'=>'--Select a country--')
);
?>
Read documentation. There is 'prompt' parameter.
Try this:
<?php
echo $form->dropDownList($model,'country_id',Country::items(), array(
'prompt' => '--Select a country--'
));
?>
See more details here http://www.yiiframework.com/forum/index.php/topic/11195-how-to-edit-the-default-option-in-dropdownlist/
You always can do something like array_merge in your items method
public static function items()
{
return array_merge(array(''=>'--Select a country--'), CHtml::listData(Country::model()->findAllBySql(
'SELECT * from country'),
'id', 'name'));
}
I believe youre looking for:
echo $form->dropDownList($model,'country_id',Country::items(),array('prompt'=>''));
if you use yiibooster maybe this will help
<?php echo $form->dropDownListGroup(
$model,
'kode_cuti_sub2',
array(
'empty'=>'--Select a country--',
'widgetOptions' => array(
'data' => array('Something ...', 'Pilih Jenis Cuti'=>Chtml::listData(Cuti::model()->cuti_sub2(),'kode','jenis_cuti')),
'options' => array(
'placeholder' => 'Pilih NIP Pegawai',
'width' => '100%',
),
),
'wrapperHtmlOptions' => array(
'class' => 'col-sm-5',
),
)
); ?>
in my case it's worked