問題描述
我是 Cake 的新手.我已經設置了一些東西,相關的用戶"和配置文件"表、控制器、模型和視圖.在我的 profiles/add
視圖中,我試圖輸出一個 select
輸入,其值為 user.id
并且選項文本為user.username
.最終,值 user.id
將保存在 profile.user_id
中.
I'm new to Cake. I've gotten some things set up, relevantly a "users" and a "profiles" table, controller, model and view. In my profiles/add
view, I'm attempting to output a select
input with the value being the user.id
and the option text being the user.username
. Ultimately, the value user.id
will be saved in profile.user_id
.
我已經閱讀了大量文檔,并成功設置了 select
以輸出 user
表中的選項,但它使用了 user.id
作為值和選項文本.
I have read through a lot of documentation, and successfully set up the select
to output the options from the user
tables, but it uses the user.id
as both the value and the option text.
控制器:
$this->set('users', $this->Profile->User->find('list'));
查看:
echo $this->Form->input('user_id');
這種事情似乎是例行公事,所以如果我完全忽略了它,請隨意回答文檔的鏈接.
It seems like this sort of thing would be routine, so feel free to answer with just a link to the documentation if I've overlooked it completely.
謝謝!
推薦答案
成功設置選擇以從用戶表中輸出選項,但它使用 user.id 作為值和選項文本.
successfully set up the select to output the options from the user tables, but it uses the user.id as both the value and the option text.
find('list')
默認使用主鍵作為鍵,模型的 displayField
作為值.
find('list')
will by default use the primary key as the key, and the model's displayField
as the value.
如果一個模型沒有明確的displayField
但是有一個名為title
或name
的字段,Cake會自動選擇這個字段,否則不會猜測并簡單地使用主鍵字段 - 這就是問題中發生的事情.
If a model does not have an explicit displayField
but has a field named title
or name
Cake will automatically pick this field, otherwise it will not guess and simply use the primary-key field - which is what's happening in the question.
然而,您可以簡單地在 find('list')
調用的結果中指定您想要的字段.因此,要么:
You can however simply specify which fields you want in the results of your find('list')
call. Therefore either:
class User extends AppModel {
public $displayField = 'username';
}
然后使用:
$users = $this->User->find('list');
顯式選擇字段
$users = $this->User->find('list', array(
'fields' => array('id', 'username')
));
在這兩種情況下 - 結果都是例如:
In both cases - the result will be e.g.:
array(
1 => 'firstuser',
...
76 => 'AD7six'
)
這篇關于CakePHP 表單選擇值作為 table.id,選擇選項文本作為 table.textfield的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!