Search code examples
cakephpselectlist

place a value of a model in a select list


I want to place fields from a model in a select list. I have this code..

brand.php & car.php models

 class Brand extends AppModel{ 
  var $name = 'Brand'; 
  var $hasMany = 'Car'; 
 }
 <?php   
 class Car extends AppModel{ 
  var $name = 'Car'; 
  var $belongsTo = 'Brand'; 
 } 
 ?>

the controller

   <?php 
   class CarsController extends AppController{
   var $name = 'Cars';
   function index(){
   $this->set('id', $this->Car->find('all'));
   }
   }
  ?>

this is the view index.ctp

<?php   
echo $form->create('Search'); 
foreach($id as $options){ 
     echo $options['Brand']['name']."<br>";  // it works
$values = array(); 
$values[] = $options['Brand']['name']; // doesnt work!

} 
echo $this->Form->select('one', $values); // the values for selects just the last one
echo $form->end('search'); 
?>

So how place the fields and id for the option values from the Brand.php model in the select list??


Solution

  • In your controller:

    $this->set('brands', $this->Car->Brand->find('list'));
    

    In your view:

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

    Cake will automagically link the $brands view var to the brand_id fields options list.