Creating 'select' listboxes using FormHelper in CakePHP

joec picture joec · Apr 17, 2010 · Viewed 14.7k times · Source

I have two models, Category and Point. The associations are defined as:

Category hasMany Point
Point belongsTo Category

I would like, when adding Points to my database, to be able to select the category it belongs to from a <select> box, along with the rest of the form data.

Where would I need to set the category list and how could I do it? And how would I produce the select box?

I assume it could be done with

$form->input('categorieslist',array('type'=>'select')); //categorieslist needs
                                                        //setting somewhere.

Answer

Abba Bryant picture Abba Bryant · Apr 20, 2010

Also to generalize a bit:

In a View with access to the Form helper

<?php
    echo $form->input( 'dataKey', array(
        'type' => 'select',
        'options' => array(
            'key1' => 'val1',
            'key2' => 'val2',
        ),
    ));
?>

The above will render a select input with two options. You can also place an empty option as the first item. Passing a value of true will simply append an empty option with a blank value to the beginning of the options rendered in the HTML.

<?php
    echo $form->input( 'dataKey', array(
        'type' => 'select',
        'options' => array(
            'key1' => 'val1',
            'key2' => 'val2',
        ),
        'empty' => true,
    ));
?>

You can pass a string to the 'empty' key to have it display custom text as the key field for the empty option.

<?php
    echo $form->input( 'dataKey', array(
        'type' => 'select',
        'options' => array(
            'California' => 'CA',
            'Oregon' => 'OR',
        ),
        'empty' => 'choose a state',
    ));
?>

One last example, you can also pre-select an option with the selected key. The value should match the value of one of the select options, not the key.

<?php
    echo $form->input( 'dataKey', array(
        'type' => 'select',
        'options' => array(
            'California' => 'CA',
            'Oregon' => 'OR',
        ),
        'empty' => 'choose a state',
        'selected' => 'California',
    ));
?>

From the Model

Model->find( 'list', array( ... )); will always return an array formatted for use with select box options. If you pass data to your view stored in a variable with a lowercase plural model name, that is, ( $this->set( 'categories', $categories );, then you will automagically generate drop downs for related models by using the form helper in the view and passing it a data index of the same model name in singular form suffixed with "_id".

Aziz's answer at #2 is the example of that automagic kicking in.