Sunday, November 26, 2017

Use find('list')

Contents

CakePHP
1. Setting up CakePHP3 with CentOS

2. Bake and Migration


4. Add a calendar page

5. Use "contain"

6. Use find('list')

find('list')


In cakephp3, find('list') is also very useful. It is used like this:
// In a controller or table method.
$products = $this->Products; //Or use table registry.
$query = $products->find('list');
$data = $query->toArray();

// Data now looks like:
// id of the record => "name" field of the table.
$data = [
    1 => 'product name 1',
    2 => 'product name 2',
];

The array data can be used as options of a HTML drop down select box:
<?php echo $this->Form->input('products', ['type'=>'select', 'options'=>$data]); ?>

If you want other field than 'name' for the value, you can specify what field should be the value:
// In a controller or table method.
$query = $articles->find('list', [
    'keyField' => 'id',
    'valueField' => 'description'
]);
$data = $query->toArray();

// Data now looks like
$data = [
    '1' => 'desctiption 1',
    '2' => 'desctiption 2',
];

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