Forms CakePHP如何使用与外键关联的值填充编辑视图中的字段?

Forms CakePHP如何使用与外键关联的值填充编辑视图中的字段?,forms,cakephp,input,view,edit,Forms,Cakephp,Input,View,Edit,遵循此问题(不是理解的必要条件) 要添加属性,请使用property.postcode字段查找匹配的postcode.postcode,然后设置property.postcode_id(用于邮政编码的外键)进行保存。Property.postcode仅供用户输入,不保存 若要编辑,系统应相同-根据邮政编码表记录检查输入的邮政编码。但是,这在编辑视图中显示了一个空字段,因为数据库中不存在Property.postcode,它只是用于数据输入 如何在编辑视图中使用postcode.postcode值

遵循此问题(不是理解的必要条件)

要添加属性,请使用property.postcode字段查找匹配的postcode.postcode,然后设置property.postcode_id(用于邮政编码的外键)进行保存。Property.postcode仅供用户输入,不保存

若要编辑,系统应相同-根据邮政编码表记录检查输入的邮政编码。但是,这在编辑视图中显示了一个空字段,因为数据库中不存在Property.postcode,它只是用于数据输入


如何在编辑视图中使用postcode.postcode值填充Property.postcode字段?

您可以首先找到所有有效的邮政编码并将其传递给视图:

echo $form->input('postcode',array(
));
在控制器中:

$pcs = $this->Property->Postcode->find('all', array
  'fields' => array('distinct(postcode) as postcode'),
));
$postCodes = array();
foreach ($pcs as $pc) {
  $postCodes[] = $pc['Postcode']['postcode'];
}
$this->set('postCodes', $postCodes);
这将简单地从相关表中获取所有唯一的邮政编码,并将其传递给视图

在视图中,您可以通过将其作为选项传递给表单输入来访问这些选项:

echo $this->Form->input('postCode', array(
  'options' -> array($postCodes)
));

希望这能有所帮助。

找到了答案!在属性控制器的编辑功能中查找邮政编码,并将其添加到请求数据中:

$postcodeRecord = $this->Property->Postcode->find('first', array(
    'conditions'=>array('id' => $this->request->data['Property']['postcode_id']),
    'fields' => array('postcode')
));
$this->request->data['Property']['postcode'] = $postcodeRecord['Postcode']['postcode'];
在视图中使用标准输入:

echo $form->input('postcode',array(
));
因为它在request->data中,所以cake将填充字段,就像值在数据库中一样。为了防止在邮政编码未更改时再次查找邮政编码,请包含检查

current $postcodeRecord === user input
如果为真,则忽略


如果有更好的方法,请务必回答

如果我理解正确,这将为用户提供一个每个可能的邮政编码可供选择的列表?这对于较小的数据集来说是理想的,但是这个表包含了它所在的每个英国邮政编码(超过200万条记录),所以它不太实用