EasyAdmin:更改分支中的formTypeOptions属性字段时出错



我有一个User实体和EasyAdmin(EA(UserCrudController来管理它们。用户实体具有活动布尔字段。我希望在管理界面中为当前用户禁用该字段。我有一个可行的解决方案:

{% extends '@EasyAdmin/crud/index.html.twig' %}
{% block table_body %}
...
{% for field in entity.fields %}

{# disable active field for current uset #}
{% if is_granted('IS_AUTHENTICATED_FULLY') %}
{% if app.user.id == entity.instance.id and field.property == 'active' %}
{% set templatePath = 'admin/crud/field/_boolean_disabled.html.twig' %}
{% else %}
{% set templatePath = field.templatePath %}
{% endif %}
{% endif %}
<td data-label="{{ field.label|e('html_attr') }}" class="{{ field.property == sort_field_name ? 'sorted' }} text-{{ field.textAlign }} {{ field.cssClass }}" dir="{{ ea.i18n.textDirection }}">
{{ include(templatePath, { field: field, entity: entity }, with_context = false) }}
</td>
{% endfor %}
...

带有重写EA布尔模板。

但我不想覆盖EA布尔模板,只想通过元素'disabled':'true'完成字段.formTypeOptions

{% for field in entity.fields %}

{# disable active field for current uset #}
{% if is_granted('IS_AUTHENTICATED_FULLY') %}
{% if app.user.id == entity.instance.id and field.property == 'active' %}
{% set field.formTypeOptions = field.formTypeOptions|merge({'disabled': 'true'}) %}
{% endif %}
{% endif %}
<td data-label="{{ field.label|e('html_attr') }}" class="{{ field.property == sort_field_name ? 'sorted' }} text-{{ field.textAlign }} {{ field.cssClass }}" dir="{{ ea.i18n.textDirection }}">
{{ include(field.templatePath, { field: field, entity: entity }, with_context = false) }}
</td>
{% endfor %}

但对于这条路径,我得到了一个错误:";未捕获的PHP异常Twig\Error\SyntaxError:"意外的令牌";标点符号";"有价值"(应为"语句块末尾"("在/home/warrant/code/blog.local/templates/admin/crud/user/index.html.twig line 27";

第27行:{%set field.formTypeOptions=field.formTypeOptions|merge({'disabled':'true'}(%}

当我这样做时:

{% set x = field.formTypeOptions|merge({'disabled': 'true'}) %}
{{ dump(x) }}
array:7 [▼
"required" => false
"row_attr" => array:1 [▶]
"attr" => array:1 [▶]
"label" => "Active"
"label_translation_parameters" => []
"label_attr" => array:1 [▶]
"disabled" => "true"
]

我得到了所需的数组,但当我尝试分配一个新的值时,我得到了相同的错误

{% set field.formTypeOptions = field.formTypeOptions|merge({'disabled': 'true'}) %}

我做错了什么?感谢

我认为这是因为merge函数不喜欢标点符号。尝试在之前将值设置为变量

更改:

{% set field.formTypeOptions = field.formTypeOptions|merge({'disabled': 'true'}) %}

收件人:

{% set options = field.formTypeOptions %}
{% set field.formTypeOptions = options|merge({'disabled': 'true'}) %}

您已经可以在UserCrudController中做到这一点,并在Twig:中避免这种逻辑

public function configureFields(string $pageName): iterable
{
// ...
// check user/roles
$isInputDisabled = true;
if($this->isGranted('ROLE_ADMIN')){
$isInputDisabled = false;
}

// ...

$active = BooleanField::new('active', 'Active')
->setFormTypeOption('disabled', $isInputDisabled);
// ...
}

最新更新