radioButtonList checked by default

2020-08-10 19:45发布

问题:

I created a option list with 2 options: Yes and No like below

<?php echo $form->radioButtonList($model,'active', array(1=>'Yes', 0=>'No'), array('separator'=>"" )); ?>

How can I set option 1 to be selected by default ?

回答1:

You have to set $model->active = 1 in your controller.



回答2:

I prefer on view page, just before the form element. as

<?php $model->isNewRecord ? $model->active = 1: $model->active = $model->active ;  ?>

This will take care of Update action also.



回答3:

You can just also set a default value in the Model itself:

Here's a form where I use a radioButtonList for reportType and have one selected by default:

class FreeReportForm extends CFormModel
{
    public $userId;
    public $email;
    public $callId;
    public $reportType = 1;
    public $companyNumber;
    public $expiry;

    ...
}


回答4:

You can set value 1 as default selected value without using $model also

<?php echo $form->radioButtonList($model,'1', array(1=>'Yes', 0=>'No'), array('separator'=>"" )); ?>


回答5:

you should add a line "$model->active=1" in your controller's function actionXXX(). for example , if the radio is in the create page, there must be a function named actionCreate() and that is the very place you add the code.



标签: yii