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.

Advertisements
Leave a comment

1 Comment

  1. Dave

     /  November 16, 2009

    Thanks for putting this out there. I was chasing all over the web trying to figure out how to get this working.

    cheers,
    dave

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: