表单中未显示自定义模型属性的验证错误



我有一个模型,它具有以下自定义属性topic_name、topic_details(字符串字段(。我还有一个具有自定义属性和自定义规则的模型表单。当我在表单字段中插入错误的数据时,会出现模型错误,但不会显示。

型号代码:

......
public function rules()
{
return [
...
[['topics_names','topics_details'],'string'],
[['topics_names'],'checkCorrectAndSetTopics'],
];
}
public function checkCorrectAndSetTopics(){
if($this->topics_names AND $this->topics_details){
$topicsNamesArray = explode(',',$this->topics_names);
$topicsDetailsArray = explode(';',$this->topics_details);
if(sizeof($topicsNamesArray) !== sizeof($topicsDetailsArray)){
$this->addError('topics_names', Yii::t('app', 'The topics names and details sets have different sizes'));
return FALSE;
}
}      
return TRUE;
}

问题是,当违反第二条规则时,表单没有显示任何错误,但确实存在。我在调试下面的代码时检查了它。

表单代码:

..........
<?php
ActiveForm::$autoIdPrefix = createRandomId();//Function which creates a random id
$form = ActiveForm::begin(
['enableAjaxValidation' => true, "options"=>  ["class"=>"extra-form"]]);
?>
<?= $form->errorSummary($model);  ?>
<?= $form->field($model, 'topics_names')->textInput()
->label(Yii::t('app', 'Topics Names'))?>
<?= $form->field($model, 'topics_details')->textarea(['rows' => 6])
->label(Yii::t('app', 'Topics Details'))?>

........   

控制器代码:

public function actionAddExtraData($id){
if(!Yii::$app->request->isAjax){
throw new ForbiddenHttpException(Yii::t('app','Cannot access this action directly.'));
}
$event = $this->findModel($id);
$extraData = ExtraData::find()
->andWhere(['event_id'=>$id])
->one();
if(!$extraData){
$extraData = new ExtraData();
$extraData->event_id = $id;
}else{
$extraData->prePerformForm();//Insert data on custom attributes
}
if(Yii::$app->request->isPost AND Yii::$app->request->isAjax AND Yii::$app->request->post("submitting") != TRUE 
AND $extraData->load(Yii::$app->request->post())){
Yii::$app->response->format = Response::FORMAT_JSON;
$validation = ActiveForm::validate($extraData);
return $validation;
}
if ($extraData->load(Yii::$app->request->post()) && $extraData->save()) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ["success" => TRUE];
} else {
return $this->redirect(Yii::$app->request->referrer);
}
}
return $this->renderAjax('_event_extra_form',['model'=>$extraData,'event'=>$event]);
}

首先,非常确定您不需要返回true或false,只需要添加错误。第二件事,在你的例子中,你命名属性,你可以在定义函数时得到它,所以你的函数看起来像这个

public function checkCorrectAndSetTopics($attribute, $model){
if($this->topics_names AND $this->topics_details){
$topicsNamesArray = explode(',',$this->topics_names);
$topicsDetailsArray = explode(';',$this->topics_details);
if(sizeof($topicsNamesArray) !== sizeof($topicsDetailsArray)){
$this->addError($attribute, Yii::t('app', 'The topics names and details sets have different sizes'));
}
}      
}

最新更新