Zoe
Zoe

Reputation: 29

How to data from yii2-widget-select2

This is my first time use of yii framework and try to use kratik widget in view. In _form.php,

$data = [
"a" => "Apple",
"b" => "Banana",
"c" => "coconut",
];

$form->field($model, 'tag[]')->widget(Select2::classname(), [
        'data' => $data,
        'options' => ['placeholder' => 'choose category', 'multiple' => true],
        'pluginOptions' => [
        'tags' => true,
        'tokenSeparators' => [',', ' '],
        'maximumInputLength' => 10
        ],
    ])->label('Select Category'); ?>

I would like to get selected data from controller. Here is my controller.php,

public function actionCreate()
{
    $model = new ChildData();
    if ($model->load(Yii::$app->request->post())) {
        $userId = Yii::$app->user->getId();
        $model->user_id= $userId;
        $model->fruit=json_encode($model->tag);
        $model->save();

        return $this->redirect(['view', 'id' => $model->id]);

    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }   
}

So, In Child table, I set fruit attribute as varchar(255). After running code,I selected all tags of fruits data from kartik widget but it only saved '[]' in fruit attribute.

Thus, I would like to know how to take data from kartik select2 in controller.php? What type of data does kartik select2 return? and how to pass selected data to view.php? Please feel free to guide me about using kartik widgets. Thank you.

Upvotes: 0

Views: 1741

Answers (1)

Irfan Ashraf
Irfan Ashraf

Reputation: 607

I assume you have a custom field declared in the model for the tag that you are using to populate the Select2. As you are not using the same field to load the model inside you actionCreate on this line.

$model->fruit=json_encode($model->tag);

To use he Select2 Single Or Multiple mode you don't need to provide the input name as an array i-e just use tag

$form->field($model, 'tag')

Change your create action to following so that you get validation errors if any.

public function actionCreate()
{
    $model = new ChildData();
    if ($model->load(Yii::$app->request->post())) {
        $userId = Yii::$app->user->getId();
        $model->user_id= $userId;
        $model->fruit=json_encode($model->tag);
        if($model->save()){
          return $this->redirect(['view', 'id' => $model->id]);
        } 

    } 
        return $this->render('create', [
            'model' => $model,
        ]);

}

Also can you please share your model code. There must be a rule defined for tag else it won't be populated. And if it is not a database field, you'll have to define a custom attribute within model i-e

public $tag;

Add a rule for tag attribute. example below

[['tag'], 'safe']

$model->load($data) populates only those attributes which have a rule defined.

Upvotes: 2

Related Questions