1
votes

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

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.

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.

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

2

2 Answers

2
votes

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(
));

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

and ignore if true.

Please do answer if there's a better way!

0
votes

You could find all of the valid postcodes first and pass it to the view:

In the controller:

$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);

This would simply get all unique postcodes from the related table and pass it to the view.

In the view you could access these for example by passing it as options to a form input:

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

Hope this helps.