Saturday, January 30, 2010

How to Generate Options for HTML Select Tags in CakePHP

How to generate options for HTML Select Tags in CakePHP?

As such

  1. You can retrieve options from a Model (Database Table).
  2. Or, you can specify options for select tag in view files.
Just keep in mind CakePHP does not support ENUM type field. So, you may not use 'ENUM' datatype in table fields.

To retrieve options from Database Table

Say, you have two Models (tables) - Order and Size; 

Fields in 'sizes' table:
id, size
And fields in 'orders' table:
id, quantity, size_id

In your OrdersController file (/app/controllers/orders_controller.php)
$sizes = $this->Order->Size->find('all');
$this->set('sizes',$sizes);

Now in your view file: (/app/views/orders/add.ctp)

echo $form->create('Order');
echo $form->input('quantity');
echo $form->input('size_id');
echo $form->end('Submit');

And done.

Note the use of variable names. 
It is important to name the variables as per this convention. It will display all sizes available in database when you are adding a new order. To retrieve size field in table 'sizes', you need to specify variable name 'sizes' (note plural form) in your respective controller/action.  Now when you refer to 'size_id' in view file - cake will create a select tag on the fly with options retrieved from database.  

OK. It was pretty simple.

Now, how to display options for HTML Select Tag without any database table:

In this case, we have, say, only 'orders' table with following fields
id, quantity, size

In your view file (/app/views/orders/add.ctp), specify - 

$form->create('Order');
$form->input('quantity');
$sizes = array('s'=>'Small', 'm'=>'Medium', 'l'=>'Large');
echo $form->input('size', array('options'=>$sizes, 'default'=>'m'));
$form->end('submit');

That's it.

2 comments:

Avo said...

hello there!... i really like the way you've posted the article... i was searching around on how to generate a dropdown, grabbing the contents from a database, having two tables "posts" and "categories"...
which is in fact exactly what your 1st case depicted is! i need to generate a categories dropdown for the "posts" add function...

however, even by preserving conventions and everything ('category_id'.. ), i get an empty dropdown :(...

am i missing something?! i really need help in this, im new to cakePHP, and feel like it's a powerful tool i can take great advantage of in creating a custom platform of my own!....

thank you in advance...
regards

my-cakephp said...

I do not know if it helps, I suppose you have missed the controller set up.. In your posts_controller.php

Use
$categories = $this->Post->Category->find('list');

and then
$this->set(compact('categories'));

...
In your view file, use
$this->Form->input('category_id');
(for cake version 1.3)
...

....
Finally set debug level to '2' and output debug($category_id)... etc... to know, if there is any other error.

..

I hope it helps.

Sid