简体   繁体   English

在CakePHP 3中对选择列表(optgroup)进行分组

[英]Grouping a select list (optgroup) in CakePHP 3

I am trying to make a list of grouped things in CakePHP 3, to create a grouped list of things in a select list in a form. 我正在尝试在CakePHP 3中创建分组列表,以在表单的选择列表中创建分组列表。 I'm not sure if I am missing something or if I'm expecting too much of Cake and should be doing more myself. 我不确定我是否缺少某些东西,或者我是否期望Cake太多而应该自己做更多的事情。

I have a controller called Issues and a self-referencing column called RelatedIssues . 我有一个名为Issues的控制器和一个名为RelatedIssues的自引用列。 Each Issue belongs to a System , and it's the systems I want the issues grouped by. 每个Issue属于一个System ,这是我希望将这些问题分组的系统。

In my IssuesTable.php : 在我的IssuesTable.php

$this->belongsTo('RelatedIssues', [
    'className' => 'Issues',
    'foreignKey' => 'issue_id'
]);

$this->belongsTo('Systems', [
    'foreignKey' => 'system_id',
    'joinType' => 'INNER'
]);

...and in my IssuesController 's edit method: ...以及我的IssuesControlleredit方法中:

$relatedIssues = $this->Issues->RelatedIssues->find('list', [
    'groupField' => 'system_id'
]);

When I get to the drop-down list, items are grouped by system_id as specified, but I cannot figure out how to get them grouped by the System 's title field. 当我进入下拉列表时,按指定的项目按system_id分组,但是我无法弄清楚如何按System的title字段对它们进行分组。 Is this even possible, or do I have to write a nice nested foreach structure to do this myself? 这是否有可能,还是我必须编写一个漂亮的嵌套的foreach结构自己完成?

should be (can'try it now): 应该是(现在可以尝试):

$relatedIssues = $this->Issues->RelatedIssues->find('list', [
    'groupField' => 'system.title'
])->contain('Systems');

Consider the following, is more clear: 考虑以下几点,比较清楚:

$relatedIssues = $this->Issues->RelatedIssues->find('list', [
        'contain' => ['Systems'],           
        'order' => [ 'Systems.title' => 'ASC', 'RelatedIssues.title' => 'ASC'],         
        'groupField' => function($entity) {
            return $entity->system->title;              
        }
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM