Yii2 - option default selection - php

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);})',
])
?>

Related

Yii2: how to format a value in ActiveField?

On my form I have this:
echo $form->field($model, 'amount')->textInput();
If the value coming from the database is 42.5 I want to have it formatted with two decimals in the input field like this 42.50. How do I do that?
I don't find any info about formatting in ActiveField docs...
You could use formatter functionalities
$form->field($model, 'amount',
['inputOptions' => ['value' => Yii::$app->formatter->asDecimal($model->amount)]])
http://www.yiiframework.com/doc-2.0/yii-i18n-formatter.html
http://www.yiiframework.com/doc-2.0/guide-output-formatting.html
As an alternative to the #scaisEdge answer, you can also override/modify the value in the ActiveField renderer.
Here's an example for an ActiveField::textInput()
<?= $form->field($model, 'vat_rate')
->textInput([
'maxlength' => true,
'placeholder' => '0.00',
'value' => (float) $model->vat_rate * 100,
]) ?>

How to set value in drop down list yii2

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']
) ?>

how to disable any dropdown field when update the from in yii2?

Here I'm stuck with one point when I open any form than i want to enable to choose one dropdown but if I want to update that from this dropdown field will be disabled.
So Which syntax I put in the form?
$form->field($model, 'branch_id', [])->dropdownList(BranchMaster::getBranchList(Common::getCurrentCompany()),
[
'class' => 'chosen-select-width branch_id',
'prompt' => Common::translateText('BRANCH_TEXT')
]
);
here is my form field ,now i want it to disable when this form is open for update action.
Try this:
<?= $form->field($model, 'branch_id', [])->dropdownList(BranchMaster::getBranchList(Common::getCurrentCompany()), [
'class' => 'chosen-select-width branch_id',
'prompt' => Common::translateText('BRANCH_TEXT'),
'disabled' => !$model->isNewRecord,
]) ?>

Radio Button group in separate place in yii2

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.

How to preselect/check a default radio button in yii2 RadioList()?

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();

Categories