Search code examples
cakephpmodelshas-and-belongs-to-many

Issue with saving HABTM data in CakePHP


I’m having an issue saving HABTM data in a controller.

I have an Article model, which is associated to an Event model, as articles may be about specific events in my application. I’ve read the CakePHP cookbook entry on saving HABTM data so understand how it works on the controller level, but having difficulties understanding how it should look on the view side of things.

What I have in my form are inputs for the article data (title, excerpt, content etc). I then want checkboxes for each event in my database then I can then check to associate an article with the corresponding event(s).

Normally, I would have a checkbox like this:

<input type="checkbox" name="event[]" value="1" />

Where 1 is the ID of a venue, and do a checkbox like this for every event in my database, but this doesn’t seem to work in CakePHP.

What should I put for my field name when creating checkboxes with $this->Form->input()? What’s the “CakePHP” way?


Solution

  • Assuming you've set the events in the controller as described in the Cook Book:

    $this->set('events', $this->Event->find('list'));
    

    then your input should look like this, basically like the example in the Cook Book, with the addition of the multiple option with an value of checkbox:

    $this->Form->input('Event', array('multiple' => 'checkbox'));
    

    This should give you a correctly formatted list of checkboxes with the events displayField as labels.

    Your next problem might be validation, so also have a look at CakePHP HABTM data not saving to database