CakePHP Table Helper
Recently, I’ve been developing a lot of sites that require the creation of a table that lists entries and has links to actions. In order to speed up development, I created a helper for CakePHP to create these tables for me.
For example, let’s say I have a list of properties in the form:
Array (  => Array ( [Property] => Array ( [id] => 12 [address_id] => 96 [description] => An okay apartment [price] => 300 [type] => apartment [num_bedrooms] => 1 ) [Address] => Array ( [id] => 96 [address1] => 650 Columbus Ave [address2] => [city] => Boston [state] => MA [zip] => 1104 ) )  => Array ( [Property] => Array ( [id] => 19 [address_id] => 98 [description] => One great apartment [price] => 500 [type] => apartment [num_bedrooms] => 1 ) [Address] => Array ( [id] => 98 [address1] => 731 Parker St. [address2] => [city] => Roxbury Crossing [state] => MA [zip] => 1104 ) ) )
I’d like to use the table creator to create a table which lists all the entries and provides action links to view the property and to edit the address. To do so, I include the helper in my controller, and then use the following code in my view.
Note that the createTable function takes in five parameters:
– the default model name
– the entries for the table
– the columns for the header. An associative array with Column Name => Database field
– the actions for the columns. An array in the form Action Name => (Action URL, Action database field)
– text to display when there are no entries.
$displayFields = array('Type' => 'type', 'Address1' => 'Address.address1', 'City' => 'Address.city', 'State' => 'Address.city', 'Price' => 'price', 'Bedrooms' => 'num_bedrooms'); $actions = array('View' => array('/properties/view/', 'Property.id'), 'Edit Address' => array('/address/edit/', 'Address.id')); echo $this->Table->createTable('Property', $properties, $displayFields, $actions, 'You currently have no properties listed' );
This code generates the following table:
For the first entry, the ‘View’ link goes to /properties/view/12 and the ‘Edit Address’ link goes to /address/edit/96.
Having this helper has definitely increased my productivity in making a lot of CRUD-based admin areas. I hope you find it helpful too. To download the source code and use it yourself, check out the github repository.