CakePHP - input select not taking select options from a variable

rickl picture rickl · Apr 28, 2013 · Viewed 13k times · Source

I am developing an application with CakePHP 2.3.2 and I am having some trouble with an input select on a form. I am creating an array, in my Controller, which contains a list of states. In my View I find that when I use this variable in the 'options' field of the input I do not get any select options. If I do a print_r on the variable, in the view, I see exactly what I think I should be seeing for the 'options' field. I have even tried copying this print_r output and putting it in the 'options' field and then the input select works fine.

Here is what I have

In Controller

$options = 'array(1 => \'NSW\',2 => \'ACT\',3 => \'NT\');
$this->set('all_states, $options);

In View

<?php
$options = $all_states;

echo $this->Form->create('Refine', array('url => '/ServiceDirectoryResults/view/refine'));

echo $this->Form->input('field' ,array(
   'type' => 'select',
   'label' => false,
   'options' => $options
));

echo $this->Form->end('Refine Search');

?>

When I run this I see a select with no select options

If I add print_r($options) after the echo $this->Form->end('Refine Search'); I see

array(1 => 'NSW',2 => 'ACT,3 => 'NT')

Which is what I would expect as it is the content of the $options variable which was the $all_states variable passed from the controller. If I take this output from the print_r and replace the $option with it in the input select the select drop down works fine and I see the three options. For some reason I can't work out the select is working fine if I hard code the select options but it will not work if I pass a variable containing the array to the input select.

I would really appreciate if if someone could give me a clue what I am doing wrong here.

Kind Regards

Richard

Answer

liyakat picture liyakat · Apr 29, 2013

you might try it like below:

echo $this->Form->input('field', array('type'=>'select','label' => false,
   'options' => $options,'default'=>'2'));

to the following HTML being generated:

<option value="2" selected="selected">ACT</option>

option two is shown instead any other one.