Symfony Form Collection-如何获取实体ID?

时间:2018-10-20 13:12:28

标签: php forms symfony twig symfony-forms

我有一个ShopCategoryCollectionType,它仅将ShopCategoryType存储为集合。

我需要访问单个ShopCategory的ID才能为实体生成编辑路径。

我已经创建了用于显示ShopCategoryWidget的自定义窗口小部件

        {{ dump(form.vars.data) }}

返回:

ShopCategory {#7325 ▼
  -id: 13
  -name: "items items"
  -slug: "items-items"
  -status: 1
  -products: PersistentCollection {#7445 ▶}
  -position: 0
}

但是当我尝试访问实体的属性

{{ dump(form.vars.data.anyAttribute) }}

我知道了

Impossible to access an attribute ("name") on a null variable.

如何获取ShopCategory实体的id属性?


编辑:

我发现了为什么会发生这种情况。

  1. 我将数据放入ShopCategoryCollectionType

     public function onPreSetData(FormEvent $event)
     {
        $data = [
            'categories' => $this->categoryRepository->findAll()
        ];
    
        $event->setData($data);
      }
    
  2. 但是当我尝试接收数据时:

    class ShopCategoryType extends AbstractType {
    
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
             $builder
            /** fields */
            ->addEventListener(FormEvents::POST_SET_DATA, function(FormEvent $formEvent) {
            dump($formEvent->getData());
        });
    }
    
  3. 结果是:

    In ShopCategoryType.php line 30:
        null
     In ShopCategoryType.php line 30:
        ShopCategory {#7574 ▼
        -id: 20
     In ShopCategoryType.php line 30:
        ShopCategory {#7575 ▼
        -id: 21
     In ShopCategoryType.php line 30:
        ShopCategory {#7576 ▼
        -id: 22
    
    /** and rest of objects */
    }
    

为什么我在第一次转储时为空?

2 个答案:

答案 0 :(得分:0)

您可以通过twig来访问表单form.vars.value中的当前数据

form.vars.value.{fieldName}

例如:

form.vars.value.name

您可以按照以下步骤显示所有字段名称:

dump(form.vars.value)

答案 1 :(得分:0)

假设您在主select c.id as clubid, c.name as clubname, l.id as layoutid, l.name as layoutname from layouts l cross join clubs c left outer join clublayouts cl on cl.layoutid = l.id and cl.clubid = c.id where cl.id is null /* and if you want the list for a single club add... */ and c.id = <some club id> 中有这个ShopCategoryCollectionType,并且FormType指向这个{{ form }}

  

FormType >> ShopCategoryCollectionType >> ShopCategoryType

,使用以下命令访问集合的条目:

FormType

0表示第一个ShopCategory