我试图用Symfony2/Twig构建一个嵌入式表单,我想在其中显示表单上每一行的映射实体的id。
我在做这个:
{% for p in form.products %}
<tr>
<td>{{p.vars.data.id}}</td>
</tr>
{% endfor %}
这很简单。。。但什么也没印。我尝试了以下方法:
{% for p in form.products %}
<tr>
<td>{{dump(p.vars)}</td>
</tr>
{% endfor %}
结果出乎意料:
array:27 [▼ "value" => ItemProduct {#857 ▼
-id: null
#enabled: false
#commission: 0.0
#support: 1
-quantity: 0
-id: 1 }
元素的两个id
属性。我甚至不知道这是可能的,我也不明白这是怎么发生的,我的代码非常简单,我以前从未遇到过这样的问题,即使是更复杂的嵌入式表单。
这是我的其余代码:
项目产品类型
class ItemProductType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder -> add ( 'artist_commission' , 'text' );
}
// ...
}
项目产品类型
class ItemProductsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('products', 'collection', array('type' => new ItemProductType()));
}
项目产品
/**
* @ORMTable(name="item_products")
* @ORMEntity(repositoryClass="APIBundleEntityItemProductRepository")
*/
class ItemProduct extends Product
{
/**
* @var integer
*
* @ORMId()
* @ORMColumn(name="id", type="integer")
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORMColumn(type="boolean")
*/
protected $enabled;
/**
* @ORMColumn(type="float")
*/
protected $commission;
/**
* @ORMColumn(type="integer")
*/
protected $support;
}
我想我终于发现了问题所在(写这个问题可能让我对代码有了新的认识)。
我的ItemProduct
继承了一个Product
类,该类有自己的id
属性。由于存在两个不同的表,并且id
属性未正确合并,Symfony使两个不同id
属性可见
由于其中只有一个实际链接到数据,另一个为空。
即使问题得到了解决,并在我的代码中揭示了更大的问题,我仍然对解释这种行为以及如何使具有相同名称的属性在实体中共存感兴趣。