在CakePHP表单中创建查找字段
我使用烘焙创建了一个具有以下内容的视图:在CakePHP表单中创建查找字段,php,cakephp,cakephp-2.1,Php,Cakephp,Cakephp 2.1,我使用烘焙创建了一个具有以下内容的视图: <fieldset> <legend><?php echo __('Edit Device'); ?></legend> <?php echo $this->Form->input('DeviceID'); echo $this->Form->input('DeviceTypeID'); echo $this->Form->input
<fieldset>
<legend><?php echo __('Edit Device'); ?></legend>
<?php
echo $this->Form->input('DeviceID');
echo $this->Form->input('DeviceTypeID');
echo $this->Form->input('UserID');
echo $this->Form->input('Type');
echo $this->Form->input('KeyPadID');
echo $this->Form->input('Version');
echo $this->Form->input('Description');
echo $this->Form->input('UpdateID');
?>
</fieldset>
我的问题是,当显示表单时,它将DeviceTypeID和UserID以及UpdateID显示为外键值,而不是标题为文本、值为ID列的下拉列表。如何将外部表中的字段设置为显示字段,将id设置为值?更新11-02-2013 首先,我强烈建议您相应地转换主键和外键 因此,它们符合CakePHP命名约定 这意味着:
应该是DeviceID
id
应该是DeviceTypeID
device\u type\u id
应该是UserID
UserID
id
。
这样你就不必担心任何事情,比如你的模型等等
之后,您的所有表格都必须是复数形式。这意味着device
表应该是devices
,所以您也应该重命名它。
我假设您还有以下表格:设备\u类型
和用户
此时,我应该注意到我更希望有一个名为devicetype
的表。我避免使用带下划线的名称,因为对每个对象、类等使用正确的形式很容易出错,所以我不必担心是否应该使用CamelCase
反正
您的设备
型号应如下所示:
<?php
/** Device.php **/
class Device extends AppModel {
public $name = 'Device';
public $belongsTo = array(
'DeviceType' => array(
'className' => 'DeviceType',
'foreignKey' => 'device_type_id'
/** Specify other keys that meet your needs **/
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
)
);
};
?>
在edit()
方法中,您应该以如下方式查询DeviceType
:
...
$devicetypes = $this->Device->DeviceType->find('list', array('id', 'caption'));
$this->set(compact('devicetypes'));
...
这样,在视图中,相应的表单元素可以正确设置
菜单
PS:您应该遵循CakePHP关于模型命名等的约定。。。我的只是一个例子 蛋糕大会+1。如果这不是根据CakePHP约定命名表和列的现有数据库,则将确保CakePHP将自动查找数据库表和关系。否则,您必须自己指定要使用的表和外键字段(这是可能的,但使用约定会节省大量时间和可能出现的问题),CakePHP也只正式支持“auto number”和“guid”(char36))列作为主键。手动输入主键可能不起作用,因为CakePHP将尝试查找具有该ID的现有记录,并“停止”保存,因为找不到该记录@thaJeztah我现在创建自动增量列只是为了确保它们不会给我带来问题。@chris sawfish我按照你的建议做了。现在我得到了一个错误:调用非对象文件上的成员函数find():D:\wamp\www\meaadmin\Controller\devicecontroller.php行:78行有
$devicetypes=$this->Device->DeviceType->find('list',array('DeviceTypeID',Type')代码>
<?php
/** DeviceType.php **/
class DeviceType extends AppModel {
public $name = 'DeviceType';
};
...
$devicetypes = $this->Device->DeviceType->find('list', array('id', 'caption'));
$this->set(compact('devicetypes'));
...