Mysql Yii2 Kartik Select2多标签输入字符串错误
我使用Select2小部件将所选标记输入存储到MySQL数据库。我希望像Mysql Yii2 Kartik Select2多标签输入字符串错误,mysql,yii2,widget,select2,Mysql,Yii2,Widget,Select2,我使用Select2小部件将所选标记输入存储到MySQL数据库。我希望像010102010103010299这样的东西存储在数据库表中 下面是视图.php echo $form->field($model, 'SpField')->label(false)->widget(Select2::className(), [ 'data' => ArrayHelper::map(Supplierfield::find()->all(), 'sfCo
010102010103010299这样的东西存储在数据库表中
下面是视图.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'],
];
}
但是,为什么我会犯这个错误。它表示输入字段必须是字符串
仅供参考:SpField
是varchar(255)的字段,sfCode
是varchar(10)的字段
非常感谢您的帮助。这是我按照@Hasiburahman的建议所做的
1。消除模型供应商中的字符串验证规则,因为小部件输入是数组形式而不是字符串
[['SpField'], 'string', 'max' => 255, 'message' => 'Field must be a string'],
2。使用json\u 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();
}
您可以使用json\u decode()
将其转换回数组,以使用选择2小部件显示$data
。就我而言
它看起来像这样的$data=json\u decode($model->SpField)代码>
对于像我这样的新手来说,这很管用。希望这也能对其他人有所帮助。使用coma值和空格内爆输入
“,”
用于查询数据库
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,
]);
}
}
多选2发布一个数组,在验证数据之前必须将其设置为字符串。请出示你的模型rule@HasiburRahaman我已经更新了问题。如何将其转换为字符串?1您可以删除此规则[['SpField'],'string','max'=>255,'message'=>'字段必须是字符串'],2)在验证之前,使用json_encode($model->SpField)将此数组转换为字符串,@HasiburRahaman我按照您的建议做了。谢谢,现在我可以使用json_encode在表中保存类似[“010101”、“010104”、“010299”、“010399”、“010501”]
的内容。但是,这就是我应该在数据库中保存标记数据的方式吗?因为我将在视图中显示它。是的,您可以这样做,当您想要显示时,使用json\u decode
function再次获取数组。