如何删除 Drupal 8 中表单树枝中的字段?

How to remove a field in the form twig in Drupal 8?

在 Drupal 8 中,表单 twig 是这样的:

<form{{ attributes }}>
  {{ children }}
</form>

我想显示除一个以外的所有字段。 通常我们使用 without 过滤器,但 children 是一个字符串,因此不会起作用。

<form{{ attributes }}>
  {{ children|without('unwanted') }}
</form>

在 twig 的形式中,我们可以访问 element 变量,它是一个数组。但是,没有过滤器在这里不起作用。

<form{{ attributes }}>
 {{ element|without('unwanted') }}
</form>

我知道我可以使用 {{ element.field }} 1 对 1 显示所有字段,但是如果我的表单有新字段,它们将不会被打印,直到我更新表单 twig。我想保持动态目的。

I do not want to update the form code in php to keep the layout in twig.

有什么想法吗?

试试这个:

{% for key in element|keys %}
    {{ children|without(key) }}
{% endfor %}

希望一切顺利...

我们找到了一个很好的答案:

  1. 创建自定义模板
{#
/**
 * @file
 *
 * Available variables
 * - form
 *
 * @see template_preprocess_mycustomform()
 *
 * @ingroup themeable
 */
#}
{{ form }}
  1. 在主题函数中声明模板
'mycustomform' => [
  'render element' => 'form',
],
  1. 将模板应用于表单
$form['#theme'] = 'mycustomform';

结果:在新模板中,我们可以使用 without twig 函数

{{ form|without('myfield') }}