A related Model isn't being validated
I currently have the following models:
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'开发者_如何学Python
)
);
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'
));
I also have this Form in the view:
<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>
My Controller:
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);
}
}
}
The problem I am having is that I could save a Post without choosing a category for it.
I've tried adding the following as a rule to the Category Model:
var $validate = array(
'rule' => array('multiple', array('in' => array(1, 2, 3, 4))),
'required' => TRUE,
'message' => 'Please select one, two or three options'
);
The Post and Page Model validates. How do I activate validation for the Category?
First off, you haven't set up the $validate
variable properly. The keys in the $validate
array must be field names. Secondly, the multiple
rule is used to check if the value(s) of a field lies within a set of values.
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'
),
),
);
I checked the example in the book for multiple
and it's a typo there. The above code is correct.
Next, if you want to validate related models, I suggest you do that in your beforeSave()
function:
function beforeSave(){
if (isset($this->data['Category']['Category']) && empty($this->data['Category']['Category'])) {
return false;
}
return true;
}
Here, returning false from the beforeSave() would prevent the save from going through. So, you will have successfully validated your requirement.
精彩评论