I was trying to build an embedded form with Symfony2/Twig in which I wanted to display the id of the mapped entity for each line on the form.
I was doing this :
{% for p in form.products %}
<tr>
<td>{{p.vars.data.id}}</td>
</tr>
{% endfor %}
which is very simple ... but nothing was printed. I tried the following :
{% for p in form.products %}
<tr>
<td>{{dump(p.vars)}</td>
</tr>
{% endfor %}
And the result was unexpected :
array:27 [▼ "value" => ItemProduct {#857 ▼
-id: null
#enabled: false
#commission: 0.0
#support: 1
-quantity: 0
-id: 1 }
Two id
attributes for the element. I didn't know it was even possible and I don't understand how this can happen, my code is extremly simple and I never encountered such issues before even with far more complex embedded forms.
Here is the rest of my code :
ItemProductType
class ItemProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder -> add ( 'artist_commission' , 'text' );
}
// ...
}
ItemProductsType
class ItemProductsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('products', 'collection', array('type' => new ItemProductType()));
}
ItemProduct
/**
* @ORM\Table(name="item_products")
* @ORM\Entity(repositoryClass="APIBundle\Entity\ItemProductRepository")
*/
class ItemProduct extends Product
{
/**
* @var integer
*
* @ORM\Id()
* @ORM\Column(name="id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="boolean")
*/
protected $enabled;
/**
* @ORM\Column(type="float")
*/
protected $commission;
/**
* @ORM\Column(type="integer")
*/
protected $support;
}
I think I've finally found what was wrong (writing the question probably made me have a new look on my code).
My ItemProduct
inherits a Product
class which has its own id
attribute. Since there are two distinct tables and the id
attribute is not merged properly Symfony makes the two different id
attributes visible.
As only one of them was actually linked to the data, the other was null.
Even if the problem is solved and revealed larger issues in my code I am still interested in explanation about this behaviour and how it is possible to make to attributes with the same name coexist in an entity.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.