开发者

Cakephp select list of numbers with corresponding values

开发者 https://www.devze.com 2023-03-21 15:50 出处:网络
I have a select list which I generate with : echo $this->Form->input(\'number_of_vehicles\', array(\'empty\' => \'Select...\', \'type\' => \'select\', \'options\' => range(1, 10, 1)));

I have a select list which I generate with :

echo $this->Form->input('number_of_vehicles', array('empty' => 'Select...', 'type' => 'select', 'options' => range(1, 10, 1)));

Now that generates a nice numbered select list from 1 to 10, incremented by 1...great. But the option value starts at 0 eg.

<select name="data[Contact][number_of_vehicles]" id="ContactNumberOfVehicles">
<option value="">Select...</option>
<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>
<option value="5">6</option>
<option value="6">7</option>
<option value="7">8</option>
<option value="8">9</option>
<option value="9">10</option>
</select>

How do you get the value to correspond to the text between the option t开发者_Python百科ags. I can circumvent the problem with javascript but its not ideal. And of course, using normal html with normal php its also easy.

What is the cake way to do this?


bear in mind that CakePHP is PHP or an extension of PHP if you want to say that. OPTIONS takes any PHP array functions there is as long as the output is what you are looking for.

For your specific need, I would suggest the array_combine PHP function. You can set it up as follows:

echo $this->Form->input(
            'number_of_vehicles',
            array(
                'empty' => 'Select...',
                'type' => 'select',
                'options' => array_combine(range(1,10,1),range(1,10,1))
            )
);

That would give you the following array which CakePHP would then magically include in your form:

Array
(
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
    [8] => 8
    [9] => 9
    [10] => 10
)

And CakePHP would generate the following html code:

...
<option value="">Select...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
...

Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消