Keyur Padalia
Keyur Padalia

Reputation: 1158

Defining default value in combobox in CakePHP

    <?php
        echo $form->create('admin_merchant_form', array('action' => '#'));
        echo $form->input('company_name', array('label' => 'Company Name'));
        echo $form->input('ac_owner',
                           array('label' => 'Account Owner',
                           'options' => array('a','b','b'),
                           'default' => $merchant_select));
        echo $form->end('Update');
    ?>

This is CakePHP code to generate a form with one combobox containing the values "a,b,c" and assigning the default value as $merchant_select which is numerical data. Now the problem is when I assign like 'default'=>1 it returns 'b' in the combobox as default value but when writing 'default' => $merchant_select the combobox shows only the first value which is 'a'.

The $merchant_select variable is assigned a numeric value equal to merchant's id which 1,2 or 3 when I select any row in the grid. And I also have JavaScript code which alerts with the merchant value when I select any row in the grid so the numeric data is definitely assigned to the $merchant_select variable.

Upvotes: 0

Views: 4681

Answers (3)

caligari
caligari

Reputation: 2128

'default' is a zero-based value, in your case you must assign ($merchant_select - 1), or much better: make the options array with key-values of merchants:

<?php

  echo $form->input('ac_owner',
    array('label' => 'Account Owner',
      'options' => array(1 => 'a', 2 => 'b', 3 => 'c'),
      'default' => $merchant_select));
?>

Upvotes: 0

Tyler
Tyler

Reputation: 2126

Default values are set by passing the index of the desired value as the 'default' parameter. In your code, you're not using an explicitly named associative array. What you want is something like:

'options' => array('a'=>'A', 'b'=>'B', 'c'=>'C'), 'default'=>'a'

You can use numeric keys too, you would just need 'default' to be 0, 1, 2, etc.

Upvotes: 1

chustar
chustar

Reputation: 12465

I'm not sure if this is controlled automatically, but the $merchant_id variable might be in a string context, rather than a numeric context. Try casting it to a number to see if that changes anything.

Upvotes: 0

Related Questions