Search code examples
cakephpformhelper

FormHelper - Pre-populated select drop-down - CakePHP


If I have:

// Controller
$this->Model->id = $id;
$this->request->data['Model'] = $this->Model->read();

And then:

// View (input field)
$this->Form->input('some_field'); // THE FORM FIELD WILL BE PRE-POPULATED

But if I want it to be a select box instead:

// View (with select)
$this->Form->select('some_field', $options); // THE SELECT BOX ISN'T PRE-POPULATED

Questions then:

a. Why isn't the select-box pre-populated like the input field is?

b. Do I really have to manually pre-populate like this?

// View (with select)
$this->Form->select('some_field', $options, array('value' => $this->request->data['Model']['some_field'])); // THE SELECT BOX IS PRE-POPULATED

c. Is the above method the most efficient method of pre-populating select boxes which already has a value?


Solution

  • no, some_field would be prepoluated by your passed form data if you would do it correctly. did you debug what you produced there? a multi-level array which is not cake standard.

    the correct approach would be:

    $this->request->data = $this->Model->read();
    

    since the array already contains the Model key (which debug() would have shown!). but careful to do this only if not posted!

    to your last question, no, if possible, use the controller or at least default. value would make your form lose the previously selected value if validation fails.

    my old cake1.3 post might also shed some light on it: http://www.dereuromark.de/2010/06/23/working-with-forms/