Etic Etic - 8 months ago 57
MySQL Question

Yii2 Kartik Select2 Multiple Tags Input String Error

I used Select2 widget to store selected tags input to MySQL database. I'am expecting something like

010102, 010103, 010299
to be stored in the database table.

Here is the view.php

echo $form->field($model, 'SpField')->label(false)->widget(Select2::className(), [
'data' => ArrayHelper::map(Supplierfield::find()->all(), 'sfCode', 'sfCode'),
'options' => [
'multiple' => true,
'placeholder' => 'Choose tag ...',
'pluginOptions' => [
'tags' => true

UPDATED : Here is the corresponding rules on the model

public function rules()
return [
[['spCode', 'SpName','SpPhone', 'SpEmail', 'SpAddress', 'SpPostcode', 'SpTown', 'SpState', 'SpDistrict','SpBumi', 'SpStatus'], 'required'],
[['RecordStamp','SpField'], 'safe'],
[['spCode'], 'string', 'max' => 7],
[['SpName', 'SpEmail'], 'string', 'max' => 50],
[['SpPhone'], 'string', 'max' => 20],
[['SpAddress'], 'string', 'max' => 100],
[['SpPostcode'], 'string', 'max' => 5],
[['SpTown', 'SpState'], 'string', 'max' => 30],
[['SpBumi', 'SpStatus'], 'string', 'max' => 15],
[['SpDistrict'], 'string', 'max' => 50],
[['spbalance','spfloatbalance'], 'number'],
[['SpField'], 'string', 'max' => 255, 'message' => 'Field must be a string'],
[['spCode'], 'unique'],

but, why am I getting this error. It says that the input field must be a string.

enter image description here

is varchar(255)'s field and
is varchar(10)'s field.

Any help is much appreciated.


This is what I've done as suggested by @HasiburRahman.

1. Eliminate the string validation rule in model Supplier because the widget input is in array form and not string.

[['SpField'], 'string', 'max' => 255, 'message' => 'Field must be a string'],

2. Convert the input into string using json_encode() and save it in the controller.

    if ($model->load(Yii::$app->request->post()) && $model->save()) 
        $model->SpField = json_encode(Yii::$app->request->post( 'Supplier' )['SpField']); //convert the array into string

You may use json_decode() to convert it back to array to display $data using the Select2 widget. In my case it look something like this $data = json_decode($model->SpField);

For now, as a newbie this work form me. Hope this will help others too.