首页 文章

我需要从控制器验证表单数据而不将其保存在CakePHP中 . 如何在每个无效字段下面显示消息?

提问于
浏览
0

我需要从控制器验证表单数据而不将其保存在CakePHP中(用于搜索目的) . 当您将数据保存到数据库时,如何在模型验证中以与id相同的方式显示每个无效字段下方的消息?

我知道有:http://book.cakephp.org/2.0/en/models/data-validation/validating-data-from-the-controller.html

它可以很好地确定是否有任何无效字段 . 但是如何以无效字段下方的标准方式(如保存数据)显示消息,最重要的是在所选视图中显示它(当控制器方法现在时,我需要在不同的视图中显示它)?

目前,如果数据无效,我会进行重定向,但如何显示特定字段的错误?

谢谢

1 回答

  • 0

    您可以使用invalidFields方法获取无效字段 . 你的代码必须是这样的 .

    <?php
    public function admin_add() {
        if ($this->Model->validates()) {
            // Do normal work here.
            ...
        }
        else {
            $invalidFields = $this->Model->invalidFields();
            // $invalidFields is an array with the field names as its key and
            // each value corresponds to its messages.
            // The array will look like this
            // array(
            //   'name' => array(
            //     'Invalid name', 
            //     'Must be 5-10 characters long'
            //   ),
            //   'password' => array(
            //     'Must not be empty',
            //     'Must be 8-12 characters long'
            // )     
            // You may past it then to the View.
            $this->set(array('invalidFields' => $invalidFields));
        }
    }
    ?>
    

    在您的视图文件上

    <form>
        <input name="name" type="text" />
        <?php if (isset($invalidFields['name'])) : ?>
        <div class="error">            
            <?php // You can print all or just the first message. Its up to you. ?>
            <?php echo $invalidFields['name'][0]; ?>
        </div>
        <?php endif; ?>
        // Other input here...
    

相关问题