php 如何在 yii2 RadioList() 中预选/检查默认单选按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31355869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to preselect/check a default radio button in yii2 RadioList()?
提问by Insane Skull
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'); ?>
回答by tarleb
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
。这意味着您应该将该属性设置为您想要预选的值:
$model->config = '1';
$form->field($model, 'config')->radioList([
'1' => 'Automatic Entry',
'2' => 'Manual Entry',
]);
The relevant doc for this is in the ActiveFormclass.
相关文档在ActiveForm类中。
回答by Mahmut Ayd?n
if you want to use default value of radio, you can use following codes:
如果你想使用radio的默认值,你可以使用以下代码:
<?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');
?>
回答by Stefan
You have to set 'config' attribute.
您必须设置“配置”属性。
$model->config = 1;
You'll have first radio button selected when form is loaded.
加载表单时,您将选择第一个单选按钮。
tarleb is right.
塔勒布是对的。
回答by methode
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.
由于我对 yii2 不是很熟悉,所以在黑暗中进行了长时间的拍摄,但是根据文档,您应该能够做这样的事情。
$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();