Ticket #1431 (closed defect: fixed)
UnitOfWork::saveRelated() not storing foreign key to newly created related record
| Reported by: | thomas.s | Owned by: | romanb |
|---|---|---|---|
| Priority: | critical | Milestone: | 1.0.1 |
| Component: | Relations | Version: | 1.0.0 |
| Severity: | Keywords: | UnitOfWork symfony embeddForm foreignKey | |
| Cc: | Has Test: | no | |
| Status: | Pending Core Response | Has Patch: | yes |
Description
I am wondering why somebody commented out essential code in UnitOfWork::saveRelated() with the comment "Can this be removed?".
/**
* saveRelated
* saves all related records to $record
*
* @throws PDOException if something went wrong at database level
* @param Doctrine_Record $record
*/
public function saveRelated(Doctrine_Record $record)
{
$saveLater = array();
foreach ($record->getReferences() as $k => $v) {
$rel = $record->getTable()->getRelation($k);
$local = $rel->getLocal();
$foreign = $rel->getForeign();
if ($rel instanceof Doctrine_Relation_ForeignKey) {
$saveLater[$k] = $rel;
} else if ($rel instanceof Doctrine_Relation_LocalKey) {
// ONE-TO-ONE relationship
$obj = $record->get($rel->getAlias());
// Protection against infinite function recursion before attempting to save
if ($obj instanceof Doctrine_Record && $obj->isModified()) {
$obj->save($this->conn);
/** Can this be removed? ts 06.09.08: I don't think so...*/
$id = array_values($obj->identifier());
foreach ((array) $rel->getLocal() as $k => $field) {
$record->set($field, $id[$k]);
}
}
}
}
return $saveLater;
}
Without the folling code
$id = array_values($obj->identifier());
foreach ((array) $rel->getLocal() as $k => $field) {
$record->set($field, $id[$k]);
}
i am unable to link a newly created related record to the other related record. To explain this: I have the relation "Profile has one Address". I use symfony 1.1 and the symfony form framework. I have two forms, ProfileForm? and AddressForm?. I embed AddressForm? in ProfileForm?.
Now, I display the ProfileForm? with an existing Profile. The Address does NOT exist at this time. The user enters address data and submits the form.
With the above code commented out (current status in r4826) the following happens:
- a new Address is created
- the Profile does not know the id of the Address and cannot connect to the Address, every form submission creates a new unrelated Address
INSERT INTO address (street_name, street_number, city, zip_code) VALUES (?, ?, ?, ?) - (my street, , , )
With the comment removed:
- a new Address is created
- Profile->address_id is set to Address->id and there is the relation
INSERT INTO address (street_name, street_number, city, zip_code) VALUES (?, ?, ?, ?) - (my street, , , ) UPDATE profile SET address_id = ? WHERE id = ? - (53, 24 )
Is there any reason not to remove that comment (that would be the patch)?