Yii2 Kartik Select2多个标签输入字符串错误

时间:2016-11-07 18:15:53

标签: mysql yii2 widget select2

我使用Select2小部件来存储输入到MySQL数据库的选定标签。我希望将010102, 010103, 010299之类的内容存储在数据库表中。

这是 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
        ]
    ]);

更新:以下是模型的相应规则

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'],
    ];
}

但是,为什么我会收到此错误。它表示输入字段必须是字符串。

enter image description here

仅供参考:SpField是varchar(255)的字段,sfCode是varchar(10)的字段。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

这就是我@HasiburRahman所建议的。

<强> 1 即可。消除模型 $scope.pattern2 中的字符串验证规则,因为窗口小部件输入是数组形式而不是字符串。

Supplier

<强> 2 即可。使用[['SpField'], 'string', 'max' => 255, 'message' => 'Field must be a string'], 将输入转换为字符串并将其保存在控制器中。

json_encode()
  

您可以使用 if ($model->load(Yii::$app->request->post()) && $model->save()) { $model->SpField = json_encode(Yii::$app->request->post( 'Supplier' )['SpField']); //convert the array into string $model->save(); } 将其转换回数组,以使用 Select2 小部件显示json_decode()。就我而言   它看起来像这样$data

对于像我这样的新手,这项工作非常好。希望这也有助于其他人。

答案 1 :(得分:1)

使用逗号值和空白空间

来破坏输入
  

&#34;,&#34;

用于查询数据库。

public function actionCreateOrUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $model->SpField = implode (", ",$model->SpField);
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create_or_update', [
                'model' => $model,
            ]);
        }
    }