2

I am trying to combine two join fields as a valueField in a dropdown combo. After checking https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#finding-key-value-pairs and How do I create a keyValue pair (display field) by combining/having two fields in CakePHP 3? I tried the following:

This works:

$authorities = $this->Books->Authorities->find('list', [
            'valueField' => 'author.name'])
            ->contain(['Authors', 'AuthorTypes']);

This works too:

$authorities = $this->Books->Authorities->find('list', [
            'valueField' => 'author_type.name'])
            ->contain(['Authors', 'AuthorTypes']);

But this doesn't:

$authorities = $this->Books->Authorities->find('list', [
            'valueField' => function ($row) {
                return $row['author.name'] . ' - ' . $row['author_type.name'];
            }])
        ->contain(['Authors', 'AuthorTypes']);

I can't understand why. Any ideas? :)

Gal Silberman
  • 3,756
  • 4
  • 31
  • 58
  • following the example [here](https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#customize-key-value-output) should be `$row->author->name` – arilia Feb 27 '18 at 14:01
  • I must be blind...because not even now can I see it is the same example ^_ ^! – RAMON RAVÉS Feb 27 '18 at 20:50

1 Answers1

1

As one of the comments suggested, follow this examples.

Your code should be:

$authorities = $this->Books->Authorities->find('list', [
            'valueField' => function ($row) {
                return $row->author->name . ' - ' . $row->author->name;
            }])
            ->contain(['Authors', 'AuthorTypes']);

This is called Customize Key-Value Output. The $row argument is an object instead of a simple array_object.

Gal Silberman
  • 3,756
  • 4
  • 31
  • 58