Checkbox Yii2:将复选框false另存为NULL
在Yii2中,我有带复选框的Checkbox Yii2:将复选框false另存为NULL,checkbox,yii2,active-form,Checkbox,Yii2,Active Form,在Yii2中,我有带复选框的ActiveForm。在mysql数据库中,tinyint(1)列可以是NULL 我需要将未选中的复选框(falsevalue)保存为数据库中的NULL。当前未选中复选框时,它将另存为(int)0 将false值保存为NULL的正确方法是什么 模型如下: class ProductToProductCategory extends ActiveRecord { public function rules() { return [
ActiveForm
。在mysql数据库中,tinyint(1)
列可以是NULL
我需要将未选中的复选框(false
value)保存为数据库中的NULL
。当前未选中复选框时,它将另存为(int)0
将false
值保存为NULL
的正确方法是什么
模型如下:
class ProductToProductCategory extends ActiveRecord {
public function rules()
{
return [
['product_category_id', 'required'],
['product_category_id', 'integer'],
['is_main', 'boolean'],
];
}
}
以下是视图:
<?= $form->field($model, "is_main")->checkbox() ?>
从未尝试过,但您应该能够通过实现已保存模型的beforeSave方法来实现
public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
return false;
}
if( $this->scenario == "strangeNullScenario" ) {
if( empty( $this->FIELD ) ) {
$this->FIELD = null;
}
}
return true;
}
只需通过取消选中选项
<?= $form->field($model, "is_main")->checkbox(['uncheck' => null]) ?>
谢谢你的建议,我知道beforeSave()
,但我不确定这样做是否正确beforeSave
全局执行,但我想将此行为限制在特定场景中,而不是将其传播到整个项目中。您应该在beforeSave中检查要保存的场景。更新答案。
<?= $form->field($model, "is_main")->checkbox(['uncheck' => null]) ?>