相关模型未经过验证

时间:2010-12-23 13:53:01

标签: validation cakephp has-and-belongs-to-many

我目前有以下型号:

class Category extends AppModel {
    var $name = 'Category';
    /*var $validate = array(
        'name' => 'multiple'
    );
        no idea how to use this
        */
    var $hasAndBelongsToMany = array(
        'Post' => array(
            'className' => 'Post'
        )
    );

class Post extends AppModel {
    var $name = 'Post';
    var $hasAndBelongsToMany = array(
        'Category' => array(
            'className' => 'Category'
        )
    );
    var $belongsTo = array(
        'Page' => array(
            'className' => 'Page'
        )
    );

class Page extends AppModel {
    var $name = 'Page';
    var $order = array('Page.modified' => 'desc');

    var $hasOne = array(
        'Post' => array(
            'className' => 'Post'
        ));

我在视图中也有这个表格:

<div id="content-wrap">
    <div id="main">
            <h2>Add Post</h2>
            <?php echo $this->Session->flash();?>
            <div>
            <?php
            echo $this->Form->create('Post');
            echo $this->Form->input('Post.title');
            echo $this->Form->input('Category.Category', array('multiple' => 'checkbox'));
            echo $this->Form->input('Post.body', array('rows' => '3'));

            echo $this->Form->input('Page.meta_keywords');
            echo $this->Form->input('Page.meta_description');

            echo $this->Form->end('Save Post');
            ?>
            </div>
    <!-- main ends -->
    </div>

我的控制器:

function admin_add() {
    // pr(Debugger::trace());
    $this->set('categories', $this->Post->Category->find('list'));

    if ( ! empty($this->data)) {

        $this->data['Page']['title'] = $this->data['Post']['title'];
        $this->data['Page']['layout'] = 'index';

        if ($this->Post->saveAll($this->data)) {
            $this->Session->setFlash('Your post has been saved', 'flash_good');
            $this->redirect($this->here);
        }
    }
}

我遇到的问题是我可以在不为其选择类别的情况下保存帖子。

我尝试将以下内容添加到类别模型中:

var $validate = array(
    'rule' => array('multiple', array('in' => array(1, 2, 3, 4))),
        'required' => TRUE,
        'message' => 'Please select one, two or three options'
);

帖子和页面模型验证。 如何激活类别的验证?

1 个答案:

答案 0 :(得分:1)

首先,您尚未正确设置$validate变量。 $validate数组中的键必须为字段名称。其次,multiple规则用于检查字段的值是否位于一组值中。

var $validate = array(
    'color' => array(
        'multiple' => array(
            'rule' => array('multiple', array('in' => array('Red', 'Blue', 'Green'))),
            'required' => false,
            'message' => 'Please select one, two or three options'
         ),
    ),
);

我查看了书中multiple的例子,这是一个错字。上面的代码是正确的。

接下来,如果您想验证相关模型,我建议您在beforeSave()函数中执行此操作:

function beforeSave(){
    if (isset($this->data['Category']['Category']) && empty($this->data['Category']['Category'])) {
        return false;
    }
    return true;
}

这里,从beforeSave()返回false将阻止保存通过。因此,您将成功验证您的要求。