Foreign key violation when saving embedded forms
The problem
For one of my symfony based project, I required to create embedded forms.
I have following schema
propel:
user:
id: ~
name: {type: varchar(100)}
password: {type: varchar(100)}
registrations:
id: ~
user_id: {type: integer, foreignTable: user, foreignReference: id, required: true}
Schema shown above is not complete, it just shows important fields only.
I generated model and form classes using propel:build-all task, and then embedded UserForm into RegistrationsForm as follow.
class RegistrationsForm extends BaseRegistrationsForm
{
public function configure()
{
unset($this['user_id']);
$user = $this->getObject()->getUser();
$userform = new UserForm($user);
$this->embedForm("User", $userform);
}
}
It works when updating an existing Registration, but when creating new registration, user_id is not set on new Registration, so no association is made between Registration and user and it gave exception of foreign key constraint violation.
The solution
So what was I doing wrong?
$user = $this->getObject()->getUser();
$userform = new UserForm($user);
This was the wrong way to create new UserForm. It works when updating an existing registration, because the user is already associated with Registration so $this->getObject()->getUser() will return an instance of User.
It won’t work when creating new Registration as $user = $this->getObject()->getUser(); will return null.
You need to check if User is null, then create a new user and set it on Registration.
Correct code
class RegistrationsForm extends BaseRegistrationsForm
{
public function configure()
{
unset($this['user_id']);
$user = $this->getObject()->getUser();
if(is_null($user)) {
$user = new User();
$this->getObject()->setUser($user);
}
$userform = new UserForm($user);
$this->embedForm(“User”, $userform);
}
}
That’s it.. it works like a charm.