如何在CakePHP中使用beforeValidate()?

cod*_*613 4 php cakephp cakephp-1.3 cakephp-model

我有一个带有URL字段的表单.该字段的默认值为:http://.但该领域不是必需的.用户可以跳过它并提交表单.它不应该返回错误,因为它不是必需的,因为它们没有输入URL.但是现在它确实如此,因为http://.

我听说我可以使用beforeValidate()检查它是否为http://,然后清除URL字段,允许我跳过错误消息.

但我不知道如何使用beforeValidate().我搜索了谷歌,但我找不到任何有用的例子.我在哪里放置beforeValidate()的代码?这是一个功能吗?如何从那里访问提交的表单数据?

谢谢.

Nik*_*kov 6

是的,beforeValidate()是模型的一个功能.所以每个型号都有它.你应该如何使用它:

class YourModel extends AppModel {
   function beforeValidate(){
      if($this->data['YourModel']['url_field'] == 'http://'){
         unset($this->data['YourModel']['url_field']);
      }
      return true; //this is required, otherwise validation will always fail
   }
}
Run Code Online (Sandbox Code Playgroud)