0

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'
        )
    );
    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?

Teej
  • 12,764
  • 9
  • 72
  • 93

1 Answers1

1

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.

RabidFire
  • 6,280
  • 1
  • 28
  • 24
  • Ok. I will try that later. My question would be, what happens when I decide to have the app be able to add a category? Wouldn't that 'multiple' rule be wrong? <-- this of course isn't related to the question. – Teej Dec 23 '10 at 16:52
  • Yes, it would be wrong for such a case. A good example of where you'd use `multiple` is the "Looking For" field in Facebook, where the user can choose multiple options between (Friendship, Dating, Relationship, Networking). – RabidFire Dec 23 '10 at 17:10
  • I don't get it. How do I go about an application now that allows me to add a category and have me choose it in a habtm when adding a post? – Teej Dec 24 '10 at 08:33
  • Exactly the way you've done it. `echo $this->Form->input('Category');` should actually suffice. You'll get a multi-select form element. When editing, Cake actually deletes previous HABTM related entries, and creates new ones. – RabidFire Dec 24 '10 at 08:34
  • Ok. assuming that I add a category, Cake will see a multiple rule which isn't very useful to it. I haven't tried it but I assume that Cake will return a false on validation. – Teej Dec 24 '10 at 09:00
  • Yes. That's correct. However, your `$validate` array is wrong as of now. It's like you're validating fields called `rule`, `required`, and `message` but these don't exist. Has your question been answered? Could you perhaps be clearer as to what exactly you want? – RabidFire Dec 24 '10 at 09:09
  • one last question. what field should I be using for the multiple rule? I assume this is for the Category model right? – Teej Dec 24 '10 at 09:18
  • If you want to *count* the number of Category models that a new Post is associated with (on save), then you need to do this in the `beforeSave` function as I've mentioned. As you've currently set up your models, you don't need to use the multiple rule anywhere. If you *really, really* want to validate against a list of Category IDs for some reason, then create a join model, and validate `category_id` with the `multiple` rule there. – RabidFire Dec 24 '10 at 09:28
  • @Thorpe - Ha ha, I just hope I was able to answer everything. :) – RabidFire Dec 24 '10 at 09:42