yii2: make checkbox to be checked - php

I am using Yii2 framework and I'd like to generate an html code like this
<input type="checkbox" id="queue-order" name="Queue[order]" value="1" checked>
in a view which uses ActiveForm.
I've tried
echo $form->field($model, 'order')
->checkBox(['label' => ..., 'uncheck' => null, 'checked' => true]);
as well as
echo $form->field($model, 'order')
->checkBox(['label' => ..., 'uncheck' => null, 'checked' => 'checked']);
but desired string "checked" does not appear in the generated html code.
Strangely enough, if I substitute "checked" with "selected"
echo $form->field($model, 'order')
->checkBox(['label' => ..., 'uncheck' => null, 'selected' => true]);
then generated html code contains attribute "selected":
<input type="checkbox" id="queue-order" name="Queue[order]" value="1" selected>
So, how can I generate html code for a checkbox with attribute "checked"?

I guess this checkbox will be checked only if $model->order property take true value and if it has false (0 or null or false etc) value - field will be unchecked.

if your are setting an external value in checkbox.
<?php $model->order = "02256"; ?>
<?= $form->field($model, "order")->checkbox(['value' => "02256"]); ?>

echo $form->field($model, 'Status')->checkbox(['uncheck' => 'Disabled', 'value' => 'Active']);

You can use checked attribute to mark it as checked
<?= $form->field($model, 'agent_email_verification')->checkbox(['checked' => $model->agent_email_verification > 0, 'value' => true]) ?>

Related

Yii2 - option default selection

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

How to use check a checkbox in CodeIgniter?

I have checkbox which is created as below in CI:
echo form_checkbox(array(
'name' => 'active',
'id' => 'active',
'value' => '1'
));
I also have other fields such as Name which have a required field validation applied. So, when I leave Name as blank and tick the active checkbox, then it shows error for name. But it removes the check on active checkbox. I want to keep the active checkbox as checked.
I know about a set_checkbox method in CI, but not sure how to use this in the above. In case of form_input we simply use set_value and all is ok. But with set_checkbox it returns full string checked="checked". So when I use the set_checkbox and form_checkbox as combined as below, then it doesn't work.
echo form_checkbox(array(
'name' => 'active',
'id' => 'active',
'value' => '1',
'checked' => set_checkbox('active', '1')
));
Any idea how to fix this?
You can set this as
echo form_checkbox(array(
'name' => 'active',
'id' => 'active',
'value' => '1',
'checked' => ($this->input->post('active') && $this->input->post('active') == 1 )
));
IF you Do not use ($this->input->post('active') && ....) in your condition it will throw an error if you do not check this check-box and submit the form.
The checked attribute on form_checkbox accepts TRUE/FALSE value. A simple comparison to see if the value is set will work.
echo form_checkbox(array(
'name' => 'active',
'id' => 'active',
'value' => '1',
'checked' => ( $this->input->post('active') == 1 )
));
The set_checkbox method was not made to be used in this style. It's intended to be use inside existing HTML as per this example from the CI User Guide
<input type="checkbox" name="mycheck" value="1" <?php echo set_checkbox('mycheck', '1'); ?> />
<input type="checkbox" name="mycheck" value="2" <?php echo set_checkbox('mycheck', '2'); ?> />

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

Yii: Make dropDownList readonly/disabled in form

I am trying to make DropDownList readonly or disable in form for update condition but my code is not working ...
echo $form->dropDownListRow($model, 'sem_id', CHtml::listData(Sem::model()->findAll(), 'id', 'title'/*, array("disabled" => "disabled")*/ , array('readonly' => 'readonly') ));
Error: call_user_func() expects parameter 1 to be a valid callback, array must have exactly two members
First thing is you should dropDownList instead of dropDownListRow. Also you forgot to use ) after 'title' And you should use "disabled" => "disabled" instead of 'readonly' => 'readonly'. I don't think they have a readonly attribute in html tags.
echo $form->dropDownList($model, 'sem_id', CHtml::listData(Sem::model()->findAll(), 'id', 'title'), array("disabled" => "disabled"));
This can make disabled dropdown list, but note that you can't relay on html attributes. Because the users can remove this attribute easily and can change dropdown value. So you need to have a control on your server.
Working example of Yii 2 dropdown disable:
<?=
$form->field($model, 'customer_status')->dropDownList([
'0' => 'Requested',
'1' => 'Registered',
'3' => 'Un-Rgistered',
'2' => 'Disabled'
], ['disabled' => 'disabled'])
?>

Categories