首页 > 解决方案 > 如何在 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>

我知道我可以用 1 by 1 显示所有字段{{ element.field }},但是如果我的表单有新字段,则在我更新表单树枝之前不会打印它们。我想保持动态目的。

不想更新 php 中的表单代码以保持树枝中的布局。

任何想法 ?

标签: formstwigdrupal-8

解决方案


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

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

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

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

推荐阅读