本文介绍了CakePHP 表单选择值作为 table.id,选择选项文本作为 table.textfield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 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.

谢谢!

推荐答案

find('list') 默认使用主键作为键,模型的 displayField 作为值.

find('list') will by default use the primary key as the key, and the model's displayField as the value.

如果一个模型没有明确的displayField但是有一个名为titlename的字段,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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 13:50