aidonsnous
aidonsnous

Reputation: 1503

Yii2 checkbox default value is not being sent to the server

Here is my code :

$model->free = true;
echo $form->field($model, 'free', ['inputOptions'=>['class'=>'form-control input-lg ']])->checkbox();

What I want is if the user doesn't uncheck, the default value must be sent to the server but my surprise, it is sending $model->free to the server null whether the user unchecks or leaves it as it is; to send the checked value, the user has to uncheck and check which stress.

How can I achieve what I want?

Upvotes: 0

Views: 2982

Answers (3)

GHopper
GHopper

Reputation: 387

In my case uncheck = false works fine:

echo $form->field($model, 'free', ['inputOptions'=>['class'=>'form-control input-lg ']])->checkbox(['uncheck' => false]);

As Chinmay mentioned, more details here

Upvotes: 1

Naim Malek
Naim Malek

Reputation: 1184

You forgot to set value attribute 'value'=>'1' to checkbox. Your code should be like.

View File

$isCheckedFree = true;
echo $form->field($model, 'free', ['inputOptions'=>['class'=>'form-control input-lg ']])->checkbox(['checked'=>$isCheckedFree,'value'=>'1']);

Controller code

if(isset($model->free) && $model->free=!null){
    $free = "Y"; // You can set your value
}else{
    $free = "N"; // You can set your value
}

Upvotes: 0

Chinmay Waghmare
Chinmay Waghmare

Reputation: 5456

Try:

echo $form->field($model, 'free', ['inputOptions'=>['class'=>'form-control input-lg ']])->checkbox( [ 'uncheck' => 0 ] );

For more details refer to link.

Upvotes: 0

Related Questions