Saturday, January 1, 2022

[FIXED] How to set the first selector value to 1 in Cake PHP Form->select

Issue

I am a new user to Cake PHP and I am going through the cake book of Cake PHP. When I am using the $this-Form->select('field', $array); the first value is always set to 0. I want this that the first selector has a value of 0.

$this->Form->select(
    'field',
    [1, 2, 3, 4, 5]
);
Output:

<select name="field">
    <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>

Can anyone help me with this query?


Solution

That's how arrays are created by default, if you don't supply keys. To use the same values for keys and values, try this:

$values = [1, 2, 3, 4, 5];
$this->Form->select(
    'field',
    array_combine($values, $values)
);


Answered By - Greg Schmidt

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.