k_schultz
k_schultz

Reputation: 111

I'm trying to retrieve from a database for a select box with cakePHP but the data isn't being retrieved properly

I am using cakephp 3.3 I have in the controller

    $employee = TableRegistry::get('employees');
    $allNames = $employee->find('list', array('employee_name' => array('employee_name') ) );
    $allNames = $allNames->toArray();
    $this->set('name', $allNames);

and in my template

    <?= $this->Form->input('employee', array('type'=>'select','label' => false,
        'options' => $name,'value'=>$name));?>

The only thing being retrieved and displayed is the number of entries i have in the database, $name only contains an array(1,2,3,4) when it should be actual people names.

Upvotes: 0

Views: 37

Answers (2)

arilia
arilia

Reputation: 9398

Did you read the documentation about how find('list') works?'

$allNames = $employee->find('list', [
    'keyField' =>     'employee_name'
    'valueField' => 'employee_name'
]);
$this->set('name', $allNames);

<?= $this->Form->input('employee', ['type'=>'select','label' => false,
    'options' => $name]);?>

Upvotes: 3

Haresh Vidja
Haresh Vidja

Reputation: 8496

You can map id and value by keyField and valueField in list query

in your controller

 $employee = TableRegistry::get('employees');
 $allNames = $employee->find('list', array('valueField' =>employee_name','keyField'=>'employee_id' )); // correct employee_id with your table id field.
 $this->set('name', $allNames);

In your View

 <?= $this->Form->input('employee', array('type'=>'select','label' => false,
        'options' => $name));?>

Upvotes: 1

Related Questions