Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: Drop down list (foreign key)

I am trying to create a drop down list for categories. If this checks out to be okay than it must be the database.

Models:

Category var $hasMany = 'Product';

Product var $belongsTo = 'Category';

ProductsController add function:

$this->loadModel('Category');
        $this->set('Categories',$this->Category->find('list',array('order'=> array('Category.name'))));
        $this->set(compact('Categories'));  
like image 479
Web Owl Avatar asked Feb 19 '23 19:02

Web Owl


1 Answers

Nebojsac is correct in that you are setting the variable "$Categories" twice in the view. In fact, $this->set(compact('Categories')); may actually be overwriting the first call to set() with a blank value. You should either use:

$this->set('categories', $this->Category->find('list'));

OR:

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

When you use compact, it is looking for a variable named $categories, and it then sets that variable to $categories to be accessible in the view.

In order for your category_id (or whatever your foreign key is) field to be automatically populated with the categories, you should make sure that you are creating the form using the form with the Product model:

echo $this->Form->create('Product');

Also, the form input should be:

echo $this->Form->input('category_id');

If you want to specify the options for your drop down manually, you can once again pass the categories to the view using $this->set('categories', $this->Category->find('list'));.

Then in your view file, set the options array key equal to $categories:

echo $this->Form->input('category_id', array('type' => 'select', 'options' => $categories));
like image 145
penguin egg Avatar answered Feb 27 '23 20:02

penguin egg