yii2 checkboxlist使用及数据入库

视图表单部分

<?php $form = \yii\widgets\ActiveForm::begin() ?>
 
<?=$form->field($model,'username')->textInput() ?>
 
<?=$form->field($model,'hobby')->checkboxList(['1'=>'篮球','2'=>'足球','3'=>'游戏','4'=>'读书'])?>
 
 
<?=\yii\helpers\Html::submitButton('保存',['class'=>'btn btn-primary'])?>
 
<?php \yii\widgets\ActiveForm::end()?>

模型部分

public function beforeSave($insert) {
    if($this->hobby) {
        $this->hobby = implode(',',$this->hobby);
 
    }
    return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
 
public function afterFind() {
    $this->hobby = explode(',',$this->hobby);
    parent::afterFind();
}
yii2.0 的 多选框实现方法

第一种:
ActiveForm::checkboxList();
 优点:可以将全部数据生成多选框,自带验证

$form->field($model, 'username')->checkboxList(ArrayHelper::map($data,'id', 'customer_name'));
第二种:
ActiveForm::checkbox();
 优点:只生成一个多选框,自带验证

$form->field($model, 'username')->checkbox(ArrayHelper::map($data,'id', 'customer_name'));
第三种:
Html::activeCheckbox();

Html::activeCheckbox($model, 'username', ArrayHelper::map($data,'id', 'customer_name'));
第四种:
Html::activeCheckboxList();

Html::activeCheckboxList($model, 'username', ArrayHelper::map($data,'id', 'customer_name'));

发表评论

电子邮件地址不会被公开。 必填项已用*标注