In Yii2 I have ActiveForm
with checkbox field. In mysql database it is tinyint(1)
column that can be NULL
.
I need unchecked checkbox (false
value) to be saved as NULL
in database. Currently when checkbox is unchecked, it is saved as (int) 0
.
What is the proper way to save false
value as NULL
?
Here is the model:
class ProductToProductCategory extends ActiveRecord {
public function rules()
{
return [
['product_category_id', 'required'],
['product_category_id', 'integer'],
['is_main', 'boolean'],
];
}
}
Here is the view:
<?= $form->field($model, "is_main")->checkbox() ?>
public function rules()
{
return [
['product_category_id', 'required'],
['product_category_id', 'integer'],
['is_main', 'boolean'],
['is_main', 'filter', function ($value) {
// return value you need
return $value ?: null;
}, 'skipOnError' => true],
];
}