Lately, I showed how you can a simply add properties to a relationship:

Doctrine 1.2: Add properties to a relationship

I continued to use this solution until I recently faced some issue for it. In fact, I discovered what I thought was a weird behavior until I completely understood the full impact of the solution.

Let’s take back our example:

N to N relationship with properties
N to N relationship with properties

I am using it in the symfony Framework, and I want to make a student form that includes also the enrolment properties. To do that, I can just use the embedded relation:

class StudentForm extends BaseStudentForm {
public function configure() {

This way, symfony automatically takes care about including the collection of enrolments into my form. And process it after the submission.

You can simply include it in your template:

$form = new StudentForm();
echo $form;

This is working pretty well!

The matter is that I want to customize my form, and thus I template it:

<form action="./submit" method="post">
<td><?php echo $form[‘name’]->render() ?></td>
<?php /* Include the collection of enrolments */ ?>
<?php foreach($form[‘Enrolments’] as $enrolment): ?>
<?php echo $enrolment[‘enrolementDate’]->render() ?>
<?php endforeach; ?>
<td colspan="2">
<input type="submit" value="Save" />
<?php /* Don’t forget hidden fields */ ?>
<?php echo $form->renderHiddenFields() ?>

Now, I have a fully customizable form… but it is not working when submit. Worse, it erases your enrolments!!! If you look into the doctrine log, I can see that you have a DELETE statement that should not be here. And then the update is done on your enrolments, even if they have been deleted.

At first, it is very strange. The reason why, is because when you embedded the enrolment relationship into your form, you also have indirectly embedded the course relationship. This is because the enrolment carries the course relationship. When symfony processes the form, it sees that you have enrolments, but you don’t have the courses that they should be bound to. So, it must be that your removed the course, and thus, the enrolments have no reason to exist anymore.

In order to work around this issue, you simply have to add the course into your form. I just did it with hidden inputs:

<?php foreach($form->getObject()->getCourses() as $course): ?>
<input type="hidden"
value="<?php echo $course->getid() ?>">
<?php endforeach; ?>

Now, when symfony processes the form, it finds the courses ids and keeps the relationship intact.

You now have a good working form!


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s