使用带有CakePhp的数字键FormHelper选择

时间:2011-01-29 21:19:30

标签: php cakephp select cakephp-1.3 formhelper

我正在使用FormHelper(cake 1.3)从数组中创建一个选择框。数组使用数字作为键,但选择框忽略这些数字,并对选择框选项值使用从零开始的索引。我已经尝试使用(字符串)$ key和strval($ key)键入数组键到一个字符串,没有运气。当我在数字键之前添加一个字母(即'c'。$ key)时,选择选项有效,但我想避免这种黑客攻击。

有没有办法强制FormHelper使用实际的数字键而不预先添加字母?任何帮助将不胜感激。

请参阅以下代码以供说明:

// $category_list looks like this
Array
(
    [164] => Antiques & Art
    [83] => Baby/Children Needs
    [176] => Boats/Marine/Fishing
    [222] => Books & Magazines
    [287] => Building Materials
    [215] => Business
    [175] => Caravans & Motor Homes
    [169] => Cars & Other Vehicles
    [127] => Clothing & Accessories
    [92] => Computers & Electronics
    [358] => Farm & Agriculture
    [235] => Garage Sales/Yard Sales
    [309] => Garden & Yard
    [178] => General Merchandise
    [138] => Health & Beauty
    [186] => Hobbies & Collectables
    [63] => Household
    [234] => Information
    [388] => Motorbikes & Scooters
    [206] => Musical Instruments
    [449] => Notices
    [305] => Pets and Accessories
    [242] => Positions Vacant
    [236] => Real Estate & Rentals
    [243] => Services
    [143] => Sports Equipment
    [308] => Tools & Equipment
    [300] => Travel & Holiday
)

// Output category select box
echo $form->select(
 'category',
 $category_list,
 $category,
 array('id'=>'SearchCategories')
);

// Outputs like this
<option value="1">Antiques &amp; Art</option>
<option value="2">Baby/Children Needs</option>
<option value="3">Boats/Marine/Fishing</option>
<option value="4">Books &amp; Magazines</option> 
...

// I'd like it to output like this
<option value="164">Antiques &amp; Art</option>
<option value="83">Baby/Children Needs</option>
<option value="176">Boats/Marine/Fishing</option> 
<option value="222">Books &amp; Magazines</option> 
...

1 个答案:

答案 0 :(得分:0)

如果您坚持惯例,您应该能够执行$ this-&gt; Form-&gt; input('category_id')并且它将起作用(将$ categories传递给视图)。 Cake确实使用数组的键作为select中的值,因此您必须传递错误的数据。

我猜你已经在数组上做了sort(),它将重置所有键。请查看php手册,了解按值保持密钥排序的方法,asort()iirc