简体   繁体   中英

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. I'm not sure if I am missing something or if I'm expecting too much of Cake and should be doing more myself.

I have a controller called Issues and a self-referencing column called RelatedIssues . Each Issue belongs to a System , and it's the systems I want the issues grouped by.

In my 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:

$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. Is this even possible, or do I have to write a nice nested foreach structure to do this myself?

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;              
        }
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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