0

我想将模型中的字段放在选择列表中。我有这个代码..

brand.php 和 car.php 模型

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

控制器

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

这是视图 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'); 
?>

那么如何将 Brand.php 模型中选项值的字段和 id 放在选择列表中?

4

2 回答 2

2

将您的find('all')呼叫更改为find('list')呼叫并在品牌模型上呼叫。

这将为您提供一个关联数组,其中包含所有记录的id=> 。您可以通过在模型中指定字段来修改显示字段displayFieldBrandvar $displayField = 'my_field';

于 2012-05-09T23:58:21.967 回答
1

在您的控制器中:

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

在您看来:

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

Cake 会自动将 $brands 视图变量链接到 brand_id 字段选项列表。

于 2012-05-10T16:05:02.077 回答