Welcome to the Cookbook

loading...

7.3.3.4 $options[‘options’]

This key allows you to manually specify options for a select input, or for a radio group. Unless the ‘type’ is specified as ‘radio’, the FormHelper will assume that the target output is a select input.

<?php echo $form->input('field', array('options' => array(1,2,3,4,5))); ?>
  1. <?php echo $form->input('field', array('options' => array(1,2,3,4,5))); ?>

Output:

<div class="input">
    <label for="UserField">Field</label>
    <select name="data[User][field]" id="UserField">
        <option value="0">1</option>
        <option value="1">2</option>
        <option value="2">3</option>
        <option value="3">4</option>
        <option value="4">5</option>
    </select>
</div>

Options can also be supplied as key-value pairs.

<?php echo $form->input('field', array('options' => array(
    'Value 1'=>'Label 1',
    'Value 2'=>'Label 2',
    'Value 3'=>'Label 3'
 ))); ?>
  1. <?php echo $form->input('field', array('options' => array(
  2. 'Value 1'=>'Label 1',
  3. 'Value 2'=>'Label 2',
  4. 'Value 3'=>'Label 3'
  5. ))); ?>

Output:

<div class="input">
    <label for="UserField">Field</label>
    <select name="data[User][field]" id="UserField">
        <option value="Value 1">Label 1</option>
        <option value="Value 2">Label 2</option>
        <option value="Value 3">Label 3</option>
    </select>
</div>

If you would like to generate a select with optgroups, just pass data in hierarchical format. Works on multiple checkboxes and radio buttons too, but instead of optgroups wraps elements in fieldsets.

<?php echo $form->input('field', array('options' => array(
    'Label1' => array(
       'Value 1'=>'Label 1',
       'Value 2'=>'Label 2'
    ),
    'Label2' => array(
       'Value 3'=>'Label 3'
    )
 ))); ?>
  1. <?php echo $form->input('field', array('options' => array(
  2. 'Label1' => array(
  3. 'Value 1'=>'Label 1',
  4. 'Value 2'=>'Label 2'
  5. ),
  6. 'Label2' => array(
  7. 'Value 3'=>'Label 3'
  8. )
  9. ))); ?>

Output:

<div class="input">
    <label for="UserField">Field</label>
    <select name="data[User][field]" id="UserField">
        <optgroup label="Label1">
            <option value="Value 1">Label 1</option>
            <option value="Value 2">Label 2</option>
        </optgroup>
        <optgroup label="Label2">
            <option value="Value 3">Label 3</option>
        </optgroup>
    </select>
</div>