4

I am very new to CakePHP. Could you please explain me the steps needed to populate a select drop-down with values from the database. Please also suggest me some links to the reference.

5 Answers 5

4

Simple, if it's a related model in your controller you pass 'list' into the find(); an cake will make an id => value array for you, and the form helper will know exactly what to do with it.

For example say you want to get the list of categories for a product model, this is in your contoller:

$categories = $this->Product->Categories->find('list');
$this->set(compact('categories'));

Then in your view using the form helper, simply create the select element how you normally would any input:

$form->input('category_id');

The form helper will automatically load the $categories variable we set with $this->set().

Sign up to request clarification or add additional context in comments.

Comments

3

You make a find in the db and then set the variable via $this->set(yourvariable) in the controller.

In the view you use the "yourvariable" in the select tag

Fill select 1

Fill select 2

Fill select 3

Comments

2

There is a cakeish way to do it with very less effort

 $this->set('arrMain',$this->Post->find('list',
                                            array(
                                                'fields'=>array('id','title')
                                                )));

Will give output as ==>

<select id="UserAge" name="data[User][Age]">
<option value="1">The title</option>
<option value="2">A title once again</option>
<option value="3">Title strikes back</option>

Comments

1

in the controller you do:

$this->loadModel('MyModel'); //if it's not already loaded
$options = $this->MyModel->find('all'); //or whatever conditions you want
$this->set('options',$options);

and in the view

<select...>
  <?php foreach ($options as $option): ?>
    <option value="<?php echo $option['MyModel']['id']; ?>"><?php echo $option['MyModel']['field']; ?></option>
</select>

3 Comments

doesnt look very cakeish^^ i prefer using the form helper
$model->find('list') is your friend.
Yes.. but find list is slower :)
1

Example

in your controller Class

$categories = $this->Articles->find('list')->select(['id', 'title'])->toArray();

$this->set(compact('categories')); // pass result dataset to the view

In Your view file

<?php echo $this->Form->select('articles_categories_id', $categories); ?>

Reading Source http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.