Embedding relations in 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:

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

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 a select dropdown with a list of currently available products.

The problem becomes apparent when you try to create a new product. Because the 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:

$this->useFields(array('filename', 'caption'));

Note: 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 the useFields method in a relation form. Symfony will then know what product_id to set on a related form when saving.

📄 View source (.md)