phpyii2active-form

check box checked by default in yii2 ActiveForm


I have ActiveForm checkbox:

<?= $form->field($model, 'is_necessary')->checkbox(['uncheck'=> 0]) ?>;

I want to make it checked by default and when I check, it's value become 1 and when uncheck - 0. Can I achieve this without any javascript?

I tried :

<?= $form->field($model, 'is_necessary')->checkbox(['uncheck'=> 0, 'value'=>false]) ?>;

option 'value'=>false made my checkbox checked by default but then in controller I receive NULL nor either 1 or 0.


Solution

  • just add in your controller or view (which is not recommended) below code

    $model->is_necessary = true;
    

    above code works fine. but you should add this code before your

    $model->load(Yii::$app->request->post)
    

    method or assigining post data to your model. Otherwise your checkbox will be checked any time;