Twig:获取附加到树枝视图Symfony中表单的实体的值



我想在TWIG视图中访问附加到表单的实体的值。

表单是这样创建的:

$form = $this->createForm(new SuperForm(), $entity);

在树枝视图中,如果我显示{{ dump(form.vars.value) }},我会显示以下内容:

Zone {#1000 ▼
#name: "First book zone"
-book: Book {#538 ▶}
-location: "inside"
-priority: 5
-live: true
-BooksGroups: PersistentCollection {#1003 ▶}
-hasGroups: true
#slug: "sdds"
#id: 2
#createdAt: DateTime {#999 ▶}
#updatedAt: null
#owner: null
#updateUser: null
}

编辑:

然而,当我试图通过这种方法访问值时,我不能:

{{ form.vars.value.name }}
Impossible to access an attribute ("name") on a null   variable

奇怪的是,当我使用去默认方法时,我没有问题,并且显示了真实值:

{{ form.vars.value.name|default('Default name') }}
Displayed: 'First book zone'

这可能是字符串和整数的变通方法,但我该如何处理集合和数组呢?

需要这个技巧,因为您可能在集合类型中设置了allow_add选项。这就是为什么第一个null来自集合的prototype,因为原型中没有设置任何值。Prototype是一个特殊的字段,不会直接在Twig中渲染。这就是为什么必须为集合中的prototype设置默认值或将allow_add设置为false

最新更新