1. 程式人生 > >yii2 checkboxlist使用及資料入庫

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'));