如何从 Twig 中的 Symfony2 表单获取 Doctrine2 实体方法

2022-01-22 00:00:00 php symfony twig

我在一个 Twig 模板中,并且我有一个表示 Doctrine2 实体表单的表单"变量.

I'm in a Twig template, and I have a "form" variable that represents a Doctrine2 Entity Form.

该实体具有映射到表单中的属性,但该实体还有一些我想从我的 Twig 模板访问的方法.

This Entity has properties that are mapped into the form, but the Entity has also some methods that I would like to access from my Twig template.

我很想做这样的事情:

{{ form.myMethod }}

或者可能是这样的:

{{ form.getEntity.myMethod }}

但不幸的是它不起作用.

but unfortunately it doesn't work.

我怎样才能达到我的需要?

How could I achieve what I need?

推荐答案

要从 twig 模板中的 FormView 访问您的实体,您可以使用以下代码

To access your entity from your FormView in a twig template you can use the following code

{{ form.get('value') }}

form 是您的 FormView 对象.这将返回您的实体,您可以从那里调用任何方法.如果您在表单中嵌入实体集合或单个实体,则可以以相同方式访问它

Where form is your FormView object. This will return your entity and from there you can call any methods on it. If you embed a collection of entities or a single entity in your form you can access it the same way

{{ form.someembedform.get('value') }}

{% for obj in form.mycollection %}
  {{ obj.get('value').someMethod }}
{% endif %}

相关文章