[英]Yii2 unique validator error display not set to form field
i am using yii2 RESTapi for my module .my problem the validation is working fne and the error msg also display in console as a json format but it's not set in form field .see the image for more info..please help me anyone ... 我为模块使用yii2 RESTapi。我的问题是验证工作正常,错误消息也以json格式显示在控制台中,但未在表单字段中设置。请参阅图片以获取更多信息。请帮助我。 。
This is model 这是模特
public function rules()
{
return [
[['username'], 'required'],
[['username'],'unique'],
}
view: 视图:
<?php $form = ActiveForm::begin([
'id' => 'cab-form',
'enableAjaxValidation' => true,
])
; ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton( 'Create', ['class' => 'btn btn-success','id'=>'submit-btn']) ?>
</div>
<?php ActiveForm::end(); ?>
controller: 控制器:
public function actionCreate(){
$model = new Cab;
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$post_data = Yii::$app->request->post();
$model->load($post_data);
$model->save();
return $model;
}
Thanks... 谢谢...
Unique require AjaxValidation to work. 唯一需要AjaxValidation才能工作。 You need verify in your controller if an ajax request exist and return the validation encoded with JSON.
您需要在控制器中验证是否存在ajax请求,并返回以JSON编码的验证。 See the example below:
请参阅以下示例:
if ($model->load(Yii::$app->request->post()) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.