0
votes

How to populate a select dropdown in cakephp3 from a database table.

Currently Cakephp produces an array (list of options) which is numeric indexed.

The option values should have id of database records (should not be the numeric keys generated by Cakephp)

Departments(table) is a taxonomy to classify events. Events(table) which should store department based list of events.

A event may belongs to many departments. How do I achieve this?

EventsController.php

<?php $department_results = $connection->execute('SELECT departmentname FROM department')->fetchAll('assoc'); // list of departments
$this->set('departmentvalues', $department_results ); 

Events: add.ctp

<?php echo  $this->Form->input('department', array('label' => false,
                                               'div' => false,
                                               'type' => 'select',
                                               'multiple'=>'checkbox',
                                               'legend' => 'false',
                                               'options' => $departmentvalues,
                                               'empty' => 'Please select a Department'
                                                 ));

Objective: A select dropdown with values from database, option values should be id of the database record

Expected result:

<select name="department"><option value="2">Maths</option><option value="4">Physics</option></select>

Issue: cakephp generates numeric indexed array of options.

<select name="department"><option value="0">Maths</option><option value="1">Physics</option></select>
2

2 Answers

1
votes

You should really use the CakePHP standard for querying your models, instead of raw SQL, especially in the case of a simple list.

Something like the below should do what you need:

$department_results = $this->Departments->find('list')
    ->hydrate(false)
    ->fields(['id','departmentname'])
    ->toArray();
$this->set('departmentvalues', $department_results);

Note that you will need to include the fields as you have named your column departmentname. By default, a find('list') should return id and name fields.

1
votes

Another option is to set the displayField this way : `class DepartmentsTable extends Table {

public function initialize(array $config) {
    parent::initialize($config);
    $this->displayField('departmentname');
}

}` In the controller you may just call the method find('list') this way :

 $departments=  TableRegistry::get("Departments");
     $departmentvalues=$departments->find('list')
                              ->hydrate(false)
                              ->toArray();
$this->set('departmentvalues', $department_results);