Yii2 表单中未显示自定义模型属性的验证错误
我有一个具有以下自定义属性的模型:主题名称、主题详细信息(字符串字段)。我还有一个带有自定义属性和自定义规则的模型表单。在表单字段中插入错误数据时,会出现模型错误,但不会显示 型号代码:Yii2 表单中未显示自定义模型属性的验证错误,yii2,Yii2,我有一个具有以下自定义属性的模型:主题名称、主题详细信息(字符串字段)。我还有一个带有自定义属性和自定义规则的模型表单。在表单字段中插入错误数据时,会出现模型错误,但不会显示 型号代码: ...... public function rules() { return [ ... [['topics_names','topics_details'],'string'], [['topics_names'],'
......
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'))?>
........
首先,非常确定您不需要返回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'));
}
}
}
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'));
}
}
}