Dropdown value for related database


#1

I baked an application based on these two tables

bookmarks

  • id
  • title
  • person_id

persons

  • id
  • name

when I now create a bookmark I have a dropdown to chose the person but instead of seeing the names I see the ids.
How can I change it to see the names

View
echo $this->Form->control(‘person_id’, [‘options’ => $persons]);

Controller
$persons = $this->Bookmarks->Persons->find(‘list’, [‘limit’ => 200]);

Thank you very much
Mattia


#2

In view file currently its $person=> Id you have to pass $ person=>Name


#3

This is what you should do.

In your src/Model/Table/PersonsTable.php , in the initialize(), add the following if it is not there:

$this->setDisplayField(‘name’);
$this->setPrimaryKey(‘id’);

// Prior to 3.4.0
$this->displayField(‘name’);

So when you call

$persons = $this->Bookmarks->Persons->find(‘list’, [‘limit’ => 200]);
$data = $persons->toArray();
$data = [1 => ‘Person 1 Name’, 2 => ‘Person 2 Name’]
You will have an array similar as below:

Details here - https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#finding-key-value-pairs


#4

Thanks, the change did exaclty what I was looking!