PHP验证错误没有显示,尽管存在于数组中


cakeCake PHP validation error not shown although existing in array

在模型中调用验证函数遇到麻烦后,我尝试从控制器进行验证。除了一个值错误的字段不显示为红色并且不显示错误消息之外,这工作得很好。

传递给视图的"validationErrors"数组是这样的:

array(
'CITY' => array(
    (int) 0 => 'Bitte eine Stadt angeben'
),
'CART' => array(
    (int) 0 => 'Bitte etwas eingeben'
),
'DATE' => array(
    (int) 0 => 'Bitte das Datum eingeben'
),
'TIME' => array(
    (int) 0 => 'Bitte die Zeit eingeben'
),
'INCOME' => array(
    (int) 0 => 'Bitte das Trinkgeld in Euro angeben'
),
'DELIVERYAREA' => array(
    (int) 0 => 'Postleitzahl existiert nicht!'
)
)

"DELIVERYAREA"是用以下代码动态构建的:

//form errors formatieren für plz-validierung
            $this->Post->set($this->request->data['Post']);
            $this->Post->validates();
            $errors = $this->Post->validationErrors + $this->Zipcode->validationErrors;
            //in $errors die keys ZIPCODE und DELIVERYAREA anlegen und zipcode löschen
            if ($this->request->data['Post']['B/S'] == 'S' && !isset($errors['ZIPCODE'])) {
                $errors['ZIPCODE'] = $errors['zipcode'];
            };
            if ($this->request->data['Post']['B/S'] == 'B' && !isset($errors['DELIVERYAREA'])) {
                $errors['DELIVERYAREA'] = $errors['zipcode'];
            };
            unset($errors['zipcode']);
            debug($errors);
            $this->set('validationErrors', $errors);

问题是所有字段都显示红色与他们的特定消息,除了deliveryarea -一个我觉得奇怪…感谢您的提前帮助

我找到了解决方案。我回到appmodel中验证,这更一致。

Cake希望自定义验证规则位于调用该规则的特定类中。因此,当您在类post中调用自定义规则时,自定义函数必须在类post中写入,否则cake不会找到它并每次都将其验证为false。

这里要做的神奇之处在于导入你想在调用验证函数的类中使用的appmodel-class。它与以下语句一起工作:

$Zipcode = ClassRegistry::init('要使用的类-在我的例子中是"Zipcode"');

但是,如果您的表与hasAny或belongsTo之类的东西相互关联,则自定义函数不需要这些就可以工作。另一个你不能错过的重要的一点是,所有的验证函数都必须用"public function xyz"来引入,否则cake也找不到它们。