forms - form_widget : Add classes to existing classes

标签 forms symfony twig

在调用 form_widget() 时,我想用 Twig 将类添加到现有类中。 -function,所以我想合并它们。但是当我使用

{{ form_widget(form.field1), {'attr': {'class': 'foo'}} }}

在 Controller 已经附加了一些类的对象上,它不会添加类,而是替换它们。根据documantation这个会

render a widget, but add a "foo" class to it



但是表述不清楚,这些类是真的“添加”了还是被替换了。

似乎我需要有一种方法来访问现有的属性/类并将它们与我想要添加的属性/类合并在一起。我怎样才能做到这一点?

最佳答案

您可能会使用 form.field1.vars.attr.class和类似 str1 ~ str2合并已经给定的类和你的新类。

把它们放在一起,你会得到:
{{ form_widget(form.field1), {'attr': {'class': form.field1.vars.attr.class ~ foo'}} }}
这有效并解决了您的问题。一些背景:

According to the symfony documentation form.field1.vars.attr is a key based array, with a class-key. So you can access all existing classes in this way.

关于forms - form_widget : Add classes to existing classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36202111/

相关文章:

forms - 有没有办法在 symfony2 中围绕输入包装标签?

javascript - div 中提交按钮时出现铁形式错误

javascript - 未捕获的类型错误 : Cannot read property 'length' of undefined when there is a parent

php - 使用 symfony2 通过 URL 自动登录

php - 如何在其他 Controller 中假脱机发送电子邮件(在任务中)并发送普通电子邮件?

css - 在 Symfony2 中使用 Twitter Bootstrap 的最佳方式是什么?

ruby-on-rails - Rails 3.2 f.file_field导致路由错误

PHP 将 $_POST 数据映射到对象

php - Symfony 4 : You have requested a non-existent parameter "locale"

javascript - 如何从js对象向twig模板添加变量