本文介绍了CakePHP如何填充编辑视图中具有与外键相关联的值的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循此问题(对理解不重要) CakePHP hasOne-belongsTo关系,如何从用户输入中查找和插入外键? / a>

Following this question (not essential for understanding) CakePHP hasOne-belongsTo relationship, how to look up and insert foreign key from user input?

要添加一个属性,将使用Property.postcode字段,用于查找匹配的Postcode.postcode,然后Property.postcode_id邮政编码)设置为保存。 Property.postcode仅用于用户输入,不会保存。

To add a property, the Property.postcode field is taken, used to find a matching Postcode.postcode, and then the Property.postcode_id (foreign key for postcode) is set for saving. Property.postcode is for user input only, it is not saved.

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

To edit, the system should be the same - postcode entered is checked against the Postcode table records. However, this presented an empty field on the edit view, as Property.postcode doesn't exist in the DB, it's just for data entry.

如何填充Property.postcode字段与编辑视图中的Postcode.postcode值?

How can I populate the Property.postcode field with the Postcode.postcode value in the edit view?

推荐答案

在Property Controller的Edit函数中查找邮政编码并将其添加到请求数据中:

Figured it out! Find the postcode in the Property Controller's Edit function and add it to the request data:

$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'];

在视图中使用标准输入:

Use a standard input in the view:

echo $form->input('postcode',array(
));

因为它在请求 - >数据中,Cake将填充该字段,就像该值在数据库中。要避免再次查找邮政编码,如果没有更改,请添加检查

Because it's in request->data, cake will populate the field as if the value was in the database. To prevent looking up the postcode again if it hasn't changed, include the check

current $postcodeRecord === user input

如果为真则忽略。

如果有更好的方法,回答。

Please do answer if there's a better way!

这篇关于CakePHP如何填充编辑视图中具有与外键相关联的值的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!