February 12, 2007
A Picklist Component for CakePHP
I needed to have a table holding all my picklists, to make them easier to edit and manage. It's a large application so there will be lots of drop downs and radio buttons, states and status fields.
I started with my picklist table
-
CREATE TABLE `picklists` (<br />
-
`id` int(11) NOT NULL auto_increment,<br />
-
`listname` varchar(20) NOT NULL,<br />
-
`item` varchar(50) NOT NULL,<br />
-
`image` varchar(50) default NULL,<br />
-
`defaultitem` int(3) NOT NULL default '0',<br />
-
`sortorder` int(4) NOT NULL default '10',<br />
-
PRIMARY KEY (`id`)<br />
-
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='to hold picklist information for any form' AUTO_INCREMENT=4 ;</p>
-
<p>INSERT INTO `picklists` VALUES (1, 'regions', 'Northland', '', 0, 1);<br />
-
INSERT INTO `picklists` VALUES (2, 'regions', 'Waikato', '', 0, 3);<br />
-
INSERT INTO `picklists` VALUES (3, 'regions', 'Auckland', '', 1, 2);
and the simplest of models.
-
class Picklist extends AppModel {<br />
-
var $name = 'Picklist';<br />
-
}
The absense of hasMany of belongsTo is for performance reasons. I don't want cakePHP getting bogged down building huge arrays everytime it hits a reference to my picklist table.
And finally the component
-
class PicklistComponent extends Object<br />
-
{<br />
-
var $controller = true;<br />
-
var $Picklist = null;</p>
-
<p>function startup(&$controller)<br />
-
{<br />
-
// This method takes a reference to the controller which is loading it.<br />
-
// Perform controller initialization here.<br />
-
$this->controller = $controller;<br />
-
loadModel('Picklist');<br />
-
$this->Picklist = new Picklist;<br />
-
}</p>
-
<p>function getlist($listname)<br />
-
{<br />
-
$picklist = new Picklist;<br />
-
$output = $this->Picklist->generateList(<br />
-
'`sortorder`, `item`',<br />
-
null,<br />
-
'{n}.Picklist.id',<br />
-
'{n}.Picklist.item'<br />
-
);<br />
-
return $output;<br />
-
}//getlist</p>
-
<p>function getfulllist($listname)<br />
-
{</p>
-
null,<br />
-
'`Picklist`.`sortorder`, `Picklist`.`item`'<br />
-
);<br />
-
return $output;<br />
-
}//getlist<br />
-
}
I don't use a controller because there is no callable interface to my picklists from this application. I'll be building an independant admin application to maintain the list - more on that later.
I started out with a picklist controller and used $this->requestAction('/picklists/getlist/reportproblem') to return the list. However on reading more I've learnt that the component is more appropriate.
Also on this site
No Comments »
No comments yet.

