Custom drop down options in Cake
Ever wanted custom options in a dropdown for your model? Let’s say you have a table called “posts” with a column called “status” and you want the following values: Published, Draft, Archived.
The way the form helper looks at options is like an array, where the array key is the option value, and the array value is the option text. So, if you pass an array that looks like this: array(‘Published’, ‘Draft’, ‘Archived’) to the options key, then the value you’ll get for “Published” will be 0 since that is its key in the array. Normally this is not what we want. You’d probably want “Published” to be the text and the option value.
A simple way to get around this and to create custom drop down options for certain tables is to stick an options variable in your model.
This is what I normally do.
In the app_model.php I would add the following function:
function getOptions() {
foreach ($this->options as $key =>$values) {
$options[$key] = array_combine($values, $values);
}
return $options;
}
In my models, if I have certain fields with custom options I would write:
class Post extends AppModel {
var $name = 'Post';
var $options = array(
'status' => array('Published', 'Draft', 'Archived');
'type' => array('Article', 'Video', 'Audio');
);
}
Now, whenever I want to set those options I would write in the controller:
$this->set('options', $this->Post->getOptions());
In your view you would then just need to write this line to set the options to the form input:
echo $form->input('status', array('options' => $options['status']));
echo $form->input('type', array('options' => $options['type']));
All done.
This would basically save the time of writing a bunch of array_combine’s in your views and it also organizes your model’s custom options.
Filed under: CakePHP, Development | Leave a Comment
No Responses Yet to “Custom drop down options in Cake”