Cakephp Form input with array options

Question

I am using cakephp 3 and using Form->input() and need to pass an array of options.

My array looks like this :

$options=['option1', 'option2', 'option3'];

I need the values of these options same as labels. Problem is, cakephp is using array index as value. So if someone selects option1, values is going 0. I need the value to be option1.

Edit :

For now, I've changed the array to look like this :

$options=['option1'=>'option1', 'option2'=>'option2', 'option3'=>'option3'];

It works, but still out of curiosity, is there any other way?


Show source
| cakephp   | php   | cakephp-3.0   2017-01-04 07:01 3 Answers

Answers ( 3 )

  1. 2017-01-04 07:01

    This is because keys of array becomes the value and value of array becomes the label/text for display in select box. Options work based on key-value pairs. e.g.

    $options=['option1'=>'option1', 'option2'=>'option2', 'option3'=>'option3'];
    echo $this->Form->select(
    'field',
    [1, 2, 3, 4, 5],
    ['empty' => '(choose one)']
    );
    

    Becomes

    <select>
     <option value='option1'>Option1</option>
     ...
     <option value='option2'>Option2</option>
    
    
     <select name="field">
       <option value="">(choose one)</option>
       <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>
    
  2. 2017-01-04 10:01

    Try this:

    In Controller

    $options = $this->YourModel->find('list', ['keyField' => 'name', 'valueField' => 'name']);
    
    $this->set(compact('options'));
    

    More info about Finding Key/Value Pairs

    In View

    <?= $this->Form->input('field', ['options' => $options ,'label' => 'Fields']); ?>
    

    or

    <?= $this->Form->select('field', $options); ?>
    

    More info about FormHelper

  3. 2017-01-05 03:01

    I wrote a couple of little helper functions for dealing with this situation.

    function make_option($value) {
        if (is_numeric($value)) {
            return $value;
        } else {
            // Translate string values
            return __($value);
        }
    }
    
    function make_options($values) {
        if (empty($values)) {
            return [];
        }
        return array_combine($values, array_map('App\Config\make_option', $values));
    }
    

    You would then use

    $options = make_options(['option1', 'option2', 'option3']);
    

    If translation isn't a concern for you, the return from your version of make_options can be simplified to just array_combine($values, $values);, and make_option can go away entirely.

◀ Go back