Reputation: 3545
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
.
Upvotes: 0
Views: 5958
Reputation: 23738
The best approach is to override init()
inside your model
public function init() {
parent::init ();
$this->is_necessary = 1;
}
and you don't need to pass the 'uncheck'=> 0,
as per the DOCS
uncheck
:string
, the value associated with the unchecked state of the radio button. If not set, it will take the default value0
. This method will render a hidden input so that if the radio button is not checked and is submitted, the value of this attribute will still be submitted to the server via the hidden input. If you do not want any hidden input, you should explicitly set this option as null.
Upvotes: 1
Reputation: 61
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;
Upvotes: 2