I have an edit form where I would like to update a number of models. The problem is that my main model, Units, belongsTo Location (since one Location can hasMany Units). The cakephp manual describes how to saveAll when your related model data belongsTo your main model, but not how it works in reverse. The code I use below obviously doesn’t update Location.address.
from edit.ctp:
<?php
echo $this->Form->create('Unit', array('url'=>array('action' =>'edit'));
echo $this->Form->input('unitnum', array('label' => 'Unit\'s Name/Number'));
echo $this->Form->input('Location.0.address');
echo $this->Form->end('Update Property');?>
And here is my controller code:
function edit($id) {
$this->Unit->id = $id;
if (empty($this->data)) {
$this->data = $this->Unit->read();
} else {
if ($this->Unit->saveAll($this->data)) {
$this->Session->setFlash('Your property has been updated.');
}
}
}
Note: I have also tried to use echo $this->Form->input(‘Location.address’); and while it beautifully pre-populates my field for me, it still doesn’t update the Location address if I change it.
UPDATE
I have discovered that when I submit my form, cake instead of updating the Location address, ADDS a new location with all the new information!
2nd UPDATE
I have also discovered that additionally, while cake will save a NEW record for the RELATED model data (that the main model belongsTo), it doesn’t update the Unit (the main model) info.
You need to pass the location ID or it will think it is a new address.
Commonly the way this is done is to show the various locations in a dropdown (id/name) that will allow you to select the location you want to add a unit to. If you already know the unit, then you should include the Location.id as a hidden field and then only display the location.address, but not as part of the form.