Reputation: 1413
I am using Kartik Select2 widget in yii2 , I've used the widget in my view and i have defined the array to show in the select to dropdown list , but when i select some of the items and post the form , it always posts null value to my controller . here is my ActiveForm in my view :
<?php
$form = ActiveForm::begin([
'options' => ['enctype' => 'multipart/form-data'],
]);
?>
<?= $form->field($model,'title')->textinput(); ?>
<?= $form->field($model,'blog')->textarea(); ?>
<?= $form->field($model,'imageFile')->fileinput(); ?>
<?=
$form->field($model, 'tag')->widget(Select2::classname(), [
'data' => $tags,
'options' => ['placeholder' => '...تگ ها را انتخاب کنید'],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
],
]);
?>
<?= Html::SubmitButton('ارسال',['class' => 'btn btn-success green']); ?>
<?php ActiveForm::end(); ?>
And here is my controller which when i check the value posted from select2 widget with var_dump
it is always null :
public function actionInsertBlog()
{
$model = new Blog();
$tagModel = new Tag();
if ($model->load(Yii::$app->request->post())) {
var_dump($model->tag);
die();
if ($model->insertBlog()) {
Yii::$app->response->redirect('?r=blog/index',301)->send();
} else {
Yii::$app->response->redirect('?r=blog/insert-blog',301)->send();
}
} else {
$tags = ArrayHelper::map($tagModel->find()->asArray()->all(),'id','tag');
return $this->render('insert',['model' => $model , 'tagModel' => $tagModel , 'tags' => $tags]);
}
}
Upvotes: 1
Views: 1720
Reputation: 713
If you are getting null value in your controller, then main reason is model rules. According to rule load function set the attribute of model that exist in model rules , May be tag attribute does not exist in your model rule. That's why it is coming null, place "tag attribute as safe in rules"
[['tag'], 'safe'],
Upvotes: 1