Embedding relations in Symfony

Posted on Category:Symfony

This quick post describes a necessary step in embedding a relation in a Symfony 1.4 form.
If you have followed Symfony’s official documentation and forums regarding embedding relations in a form, you may have already seen an example of product and productPhoto forms in a single form.
Here’s the schema:
[php]
Product:
columns:
name: { type: string(255), notnull: true }
price: { type: decimal, notnull: true }

ProductPhoto:
columns:
product_id: { type: integer }
filename: { type: string(255) }
caption: { type: string(255), notnull: true }
relations:
Product:
alias: Product
foreignType: many
foreignAlias: Photos
onDelete: cascade
[/php]
Now, when you’re creating/editing the productPhoto form, it’s of paramount importance to tell Symfony not to use product_id field in a form, because that would render an select dropbox with a list of currently available products.
The problem becomes apparent when you try to create new product. Because new product does not yet have a product_id, your product photo will be saved with another product that’s currently selected.
The solution is to use line:
[php]
$this->useFields(array(‘filename’, ‘caption’));
[/php]
[info] If you try to hide product_id field in a form, editing of an existing product will work fine, but you’ll get a “Required field” error when trying to save a new product, so it’s very important to use useFields method in a relation form. Symfony will then know what product_id to set on a related form when saving.[/info]