2
votes

Using the form helper in Cakephp 1.3, I'm trying to display a list (drop-down list) which contains several duplicates value fields (in <option> tag of course), but cake seems not to want to let me doing it, and outputs only the first occurrence of each value.


For instance, here's the 'options' array of the $form->input:

array(
    0 => 'description 0',
    0 => 'description 1',
    0 => 'description 2',
    1 => 'description 3'
);


Which will output something like:

<select>
    <option value="0">description 0</option>
    <option value="1">description 3</option>
</select>

And I'm looking for this result:

<select>
    <option value="0">description 0</option>
    <option value="0">description 1</option>
    <option value="0">description 2</option>
    <option value="1">description 3</option>
</select>


Cheers,
Nicolas.

2

2 Answers

1
votes

Of course you cannot use the same key twice in an array in PHP.

But as stated on this article cake knows how to make multiple keys with the same value in 2.x:

$options = array(
    ...
    array('name' => 'United states', 'value' => 'USA'),
    array('name' => 'USA', 'value' => 'USA'),
 );

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

resulting in

<option value="USA">United states</option>
<option value="USA">USA</option>

As you can see, you got your value here twice (or more of course) now.

See the documentation of the form helper class itself (cake2.x). Not sure if 1.3 does already support it, though.

If you upgrade, you will be able to leverage all of cake's newest magic.

0
votes

So as feared the problem was deeper than I first thought , and it was caused by PHP which does not (obviously) allow duplicate keys.

So here's my solution (if anyone's interested in):

  1. Create a new helper extending the FormHelper
  2. Copy the original function __selectOptions() from the form helper into your new helper
  3. Just change this line:
    foreach ($elements as $name => $title) {
    by :
    foreach ($elements as $title => $name) {
  4. Done!

It's not the best solution as if you want to update your cakephp to the latest version after doing that, you have to copy/paste the function again, and do the same trick.


How to use it:

  1. Declare your options array the other way around : array('description' => 'key);
  2. In your view, instead of doing $form->input, just do $yourhelper->input


Nicolas.