一千萬個為什麽

搜索

使用CakePHP中的FormHelper創建“選擇”列表框

我有兩個模型, CategoryPoint 。這些關聯定義為:

Category hasMany Point
Point belongsTo Category

I would like, when adding Points to my database, to be able to select the category it belongs to from a

最佳答案

還要概括一下:

在可以訪問表單助手的視圖中

<?php
    echo $form->input( 'dataKey', array(
        'type' => 'select',
        'options' => array(
            'key1' => 'val1',
            'key2' => 'val2',
        ),
    ));
?>

以上將使用兩個選項呈現選擇輸入。您還可以將空選項作為第一項。傳遞值true將簡單地將帶有空值的空選項附加到HTML中呈現的選項的開頭。

<?php
    echo $form->input( 'dataKey', array(
        'type' => 'select',
        'options' => array(
            'key1' => 'val1',
            'key2' => 'val2',
        ),
        'empty' => true,
    ));
?>

您可以將字符串傳遞給“空”鍵,以使其顯示自定義文本作為空選項的關鍵字段。

<?php
    echo $form->input( 'dataKey', array(
        'type' => 'select',
        'options' => array(
            'California' => 'CA',
            'Oregon' => 'OR',
        ),
        'empty' => 'choose a state',
    ));
?>

最後一個示例,您還可以使用所選鍵預選一個選項。該值應與其中一個選擇選項的匹配,而不是與鍵匹配。

<?php
    echo $form->input( 'dataKey', array(
        'type' => 'select',
        'options' => array(
            'California' => 'CA',
            'Oregon' => 'OR',
        ),
        'empty' => 'choose a state',
        'selected' => 'California',
    ));
?>

從模型

Model->find( 'list', array( ... )); will always return an array formatted for use with select box options. If you pass data to your view stored in a variable with a lowercase plural model name, that is, ( $this->set( 'categories', $categories );, then you will automagically generate drop downs for related models by using the form helper in the view and passing it a data index of the same model name in singular form suffixed with "_id".

Aziz's answer at #2 is the example of that automagic kicking in.

轉載註明原文: 使用CakePHP中的FormHelper創建“選擇”列表框