Symfony: update a related table with the id for newly saved records?
I have the base table called SnUser
and a related table, SnAltceva
:
SnUser:
columns:
name: { type: string(100) }
age: { type: integer(1) }
level_id: integer
relations:
SnAltceva: { local: id, foreign: user_id }
SnAltceva:
columns:
user_id: integer
field_1: string(10)
field_2: integer(1)
relations:
SnUser:
local: user_id
foreign: id
onDelete: CASCADE
I created SnUser form and embedded it with a new SnAltceva
form. Everything works 开发者_如何学Cwell, sn_user
table is updated with the new record, also the sn_altceva
but the user_id
is NULL.
My wish is to update this field also with the newly inserted if from SnUser
.
I suspect I need to override save()
from /lib/model/doctrine/SnUser.class.php
but not quite sure how.
Any suggestions?
Found it:
class SnUserForm extends BaseSnUserForm {
public function configure() {
// get the SnAltceva object reference (embeded one)
// if not, create a new one
$altObj = $this->getObject()->getSnAltceva();
if( is_null($altObj) ) {
$altObj = new SnAltceva();
$this->getObject()->setSnAltceva($altObj);
}
// create the form with the already linked obj
$formAlt = new SnAltcevaForm($altObj);
$this->embedForm('altceva', $formAlt);
}
}
No need to override the save() method in SnUser() class. The related table will be automatically saved with the right (fresh) id.
Hope it helps others on the future.
You need to override save to fist save the user object. then get the object from the embedded form for Altceva and set the user id on it. then save that object.
sfGuardPlugins (both Doctrine and Propel) ave a good examle of this when it comes to User/UserProfile saves. You can use that as a reference.
精彩评论