Cakephp 2.3:如何不使用“id"作为 $belongsTo <select> 的标签选项 [英] Cakephp 2.3: How to not use 'id' as the label of $belongsTo <select> options
问题描述
我在使用 Cakephp 时经常遇到这种困境,我很确定这是我没有遵循/理解某处约定的结果.在任何类型的 belongsTo
(hasAnd 或其他)中,我通常发现由于 id
往往是外键,它也最终显示在下拉菜单中,这在语义上当然是无用的.
I run into this dilemma a lot with Cakephp, and I'm prettty sure it's a consequence of my not following/understanding a convention somewhere. In any kind of belongsTo
(hasAnd or otherwise), I generally find that since id
tends to be the foreign key, it also ends up being what is displayed in dropdown menus, and this is of course semantically useless.
这是我通常所做的一个例子;我希望有人可以让我直截了当:(我只是制作这些表格,因为它们为一般问题提供了一个很好的模板.)
Here's an example of what I've generally done; I'm hoping someone can set me straight: (I'm just making up these tables because they make a good template for the general problem.)
假设:
Users
表有列 id
|firstname
|lastname
Accounts
有 id
|user_id
(我所做的没有这么简单,但这是问题的一般形式)
使用cake bake all
,我的Accounts/add
视图为user_id
构建了一个下拉菜单,从字面上显示ID 号.我找到了几种方法来解决这个问题,但它们基本上都涉及我自己组装信息.我要么在控制器中为 Accounts/add
的 user_id
下拉列表构建一个 $options
数组,如下所示:
Using cake bake all
, my Accounts/add
view builds a dropdown for user_id
that literally displays ID numbers. I have found a couple of ways around this, but they all involve basically assembling the information myself. I've either done it by building, in the controller, an $options
array for the user_id
dropdown of Accounts/add
like so:
控制器
$users = $this->Account->User->find('list');
$options = Set::combine($users, '{n}.User.id', array('{0} {1}', '{n}.User.firstname', '{n}.User.lastname'));
查看
echo $this->Form->input('user_id', array('div' =>数组('id' =>'UserId'),'options'=>$options,'type'=>'select') )."
";
echo $this->Form->input('user_id', array(
'div' => array( 'id' =>'UserId'),
'options'=>$options,'type'=>'select'
) )."
";
或者通过:
控制器
$users = $this->Account->User->find('all', array('recursive' => 1));
然后以几乎相同的方式解析 View 中的数据.在任何一种情况下,我始终有一种挥之不去的确定性,即我可以以解决这个问题的方式构建我的模型——这似乎太基本了,没有被如此广泛的框架解决.
And then parsing the data at the View in almost the same fashion. In either case, I've always had the lingering certainty that I could be building my models in such a way that addresses this—it just seems like too basic a need to have not been addressed by such an extensive framework.
推荐答案
对于单列表,简单的 $displayField = 'column_name' 就是答案.
For single column tables, a simple $displayField = 'column_name' is the answer.
但是对于列的串联,涉及更多的代码:
But for concatenations of columns, there's a bit more code involved:
public $virtualFields = array("full_name"=>"CONCAT(first_name, ' ' ,last_name)");
public $displayField = 'full_name';
如果它是一个非常复杂的 $displayField,则可能需要使用 afterFind 解决方案,但在大多数情况下,这就是解决方案.
If its a really complicated $displayField, an afterFind solution may be necessary, but for most cases this is the solution.
希望有所帮助.
这篇关于Cakephp 2.3:如何不使用“id"作为 $belongsTo <select> 的标签选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!