【问题标题】:Can Cake Php Validation clear input field valueCake Php Validation能否清除输入字段值
【发布时间】:2012-05-02 10:50:53
【问题描述】:

Cake Php Validation 能否清除输入字段值

var $validate = array(
    'name' => array(
       'isUnique' => array (

           'rule' => 'isUnique',

           'message' => 'This Person name already exists.'
       )
    )
);

如果验证中仍然存在错误,我想清除 name 字段值。是否可以通过 cake php 验证本身来做到这一点?

【问题讨论】:

    标签: cakephp cakephp-1.3


    【解决方案1】:

    如果需要,您可以使用自定义验证规则来实现。

    var $validate = array(
        'name' => array(
           'isUnique' => array (
               'rule' => 'ifNotUniqueClear', // use custom rule defined below
               'message' => 'This Person name already exists.'
           )
        )
    );
    
    function ifNotUniqueClear(&$data) {
        $field = key($data);
    
        // see if the record exists
        $user = $this->find('first', array(
            'conditions' => array(
                $field => $data[$field]
            ),
            'recursive' => -1
        ));
    
        if ($user) {
            // unset or empty it, your choice
            unset($this->data[$this->alias][$field]);
            return false;
        }
    
        return true;
    }
    

    【讨论】:

    • 我用上面的代码试过了,但是对应的文本字段没有被清除。当我print_r($this->data)时,对应的变量未设置,仍然输入字段显示对应的值..
    • 您是否检查了验证规则中的$this->data?是否符合验证规则?是否找到用户(验证规则中的debug($user))。
    • 是的,$this->data 在验证规则中。 debug($user) 将给出对应的$user 详细信息的数组。
    • 您的控制器操作是否对数据进行了处理?其他行为?如果数据在到达视图时未设置,则不应填充该字段。另外,试试$this->data[$this->alias][$field] = '',只是出于好奇。
    猜你喜欢
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多