遵循这个问题(对于理解不是必不可少的)CakePHP hasOne-belongsTo relationship, how to look up and insert foreign key from user input?
要添加属性,将使用Property.postcode字段,用于查找匹配的Postcode.postcode,然后设置Property.postcode_id(用于邮政编码的外键)进行保存。 Property.postcode仅供用户输入,不保存。
要进行编辑,系统应该相同 - 输入的邮政编码将根据邮政编码表记录进行检查。但是,这在编辑视图中显示一个空字段,因为DB中不存在Property.postcode,它仅用于数据输入。
如何在编辑视图中使用Postcode.postcode值填充Property.postcode字段?
答案 0 :(得分:2)
想出来!在Property Controller的编辑功能中找到邮政编码,并将其添加到请求数据中:
$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->数据中,所以cake会填充该字段,就好像该值在数据库中一样。要防止在未更改后再次查找邮政编码,请添加检查
current $postcodeRecord === user input
并忽略if true。
如果有更好的方法,请回答!
答案 1 :(得分:0)
您可以先找到所有有效的邮政编码,然后将其传递给视图:
在控制器中:
$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)
));
希望这有帮助。