Get Items for a Dropdown in CakePHP 4

Get Items to Populate a Dropdown in CakePHP 4

In this example, we have a table for states and their abbreviation.  This code returns those 2 fields only, so they can readily be used in a dropdown.

In your controller:

$this->loadModel('States');
$states = $this->States->find('list', [ 'keyField'=> 'abbr', 'valueField'=>'name' ] )->toArray();
​$this->set('states', $states);

 

In your view:

echo $this->Form->control('state', 
  [
     'class' => 'form-control', 'label'=>'State', 'options' => $states, 
      'empty' => 'Choose a State'
   ]);

Share this Post