Category: Views

Q: Create dropdown list in CakePHP

I use CakePHP's form helper to generate <form></form> columns, but I didn't see a helper that is able to create dropdown list. I use foreach to list all possible options..

<!-- in view /registers.ctp -->
<?= $this->Form->create('Users', array('type' => 'post', 'url' => ['controller' => 'users', 'action' => 'register']); ?>

<!-- Country Select -->
<select>
<?php foreach ($countries as $country): ?>
  <option value="<?= $country['code']; ?>"><?= $country['name']; ?></option>
<?php endforeach; ?>
</select>

SOLVED select htmlhelper
2 Answers

Version: 3.3

user
Lara

4

Accepted by Lara

Use $this->Form->select() or $this->Form->input('name', ['options' => array()]); if you do not want to do foreach loop.

Controller file:

//controller
// 'value' => 'name'
$countries_list = [
    'US' => 'United State',
    'CA' => 'Canada',
    'CN' => 'China',
    //...etc
];

$this->set('countries', $countries_list); 

View /registers.ctp

<!-- in view /registers.ctp -->
<?= $this->Form->create('Users', array('type' => 'post', 'url' => ['controller' => 'users', 'action' => 'register']); ?>

<!-- Country Select -->
<?= $this->Form->input('country', [
    'options' => $countries,
    'default' => $default_value,
    'selected' => $selected_value
    ]); ?>

Form Helper

Kristi
Kristi

137

You need Form select,

<!-- Country Select -->
<?= $this->Form->select('country', $countries); ?>