Reading the CakePHP group messages, a lot of people seem to run into problems with creating HABTM relationships and changing from the default multipleSelect to using a series of checkboxes. In an app I was building I ran into a brick wall where I just wasn’t able to find out waht was wrong so I just decided to bake a quick example that I could use as a reference.
This is for Cake 1.1.x.x
I used a slightly modified copy of the SQL from the manual and used Josh McFarren’s checkbox helper.
--
-- Table structure for table `posts`
--
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL auto_increment,
`title` varchar(50) default NULL,
`body` text,
`created` datetime default NULL,
`modified` datetime default NULL,
`status` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`)
) TYPE=MyISAM;
-- --------------------------------------------------------
--
-- Table structure for table `posts_tags`
--
CREATE TABLE `posts_tags` (
`post_id` int(10) unsigned NOT NULL default '0',
`tag_id` int(10) unsigned NOT NULL default '0',
PRIMARY KEY (`post_id`,`tag_id`)
) TYPE=MyISAM;
-- --------------------------------------------------------
--
-- Table structure for table `tags`
--
CREATE TABLE `tags` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(100) default NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM;
I have made two changes to the SQL above:
- Removed the user_id field in ‘posts’ (to simplify the example)
- Changed ‘tag’ to ‘name’ in ‘tags’ – I changed this because generateList was not working and the $tags array geneated for the view did not contain the tag name ‘tag’ – only the ‘tag_id’ value.
You can download my working example, it contains all of the files that I create in bake and the files added and changed to use the checkboxHelper. To install the example:
- Bake a new application
- Connect to database
- Paste files from zip example to replace the newly baked files
- Create database tables using the SQL
HABTM_checkbox_example.zip