How to populate a drop-down list with database values ​​in CakePHP

I am very new to CakePHP. Could you explain to me the steps required to populate a drop-down list with values ​​from the database. Please also offer me links to the link.

+4
source share
5 answers

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

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

Fill in selection 1

Fill selection 2

Fill Choice 3

+3
source

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

For example, say you want to get a 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 a select element, as you would normally type:

 $form->input('category_id'); 

The form assistant will automatically load the $ categories variable that we set using $ this-> set ().

+4
source

There is a way to head it out with less effort.

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

Gives 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> 
+2
source

in the controller that you do:

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

and in view

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

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

+1
source

Source: https://habr.com/ru/post/1340537/


All Articles