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); ?>

Created: 3 Oct '16

Last Reply: 3 Oct '16

Replies: 2

Views: 746

Votes: 0

Welcome to Aero Coding!

Aero Coding is a CakePHP-focused Q&A community for professional and enthusiast cake bakers. It's built and run by you as part of the community.


Join Now Tour

Download Cakephp

Start baking your own CakePHP application!


Cakephp All Versions