我想在Symfony中的ChoiceType字段中添加一个额外的注解。这是我的方法。它工作正常,但我很好奇是否有更好的方法。
在我的控制器中,我有一个注解数组,并将数组传递给我的formType。数组的值也可以包含一些HTML标记。
$comments[0] = 'Lorem ipsum dolor sit amet,consectetur adipiscing elit. Praesent nec pellentesque velit, ut porta erat. Etiam convallis rhoncus erat vitae sodales. Vivamus porta tellus erat, non congue urna blandit eget. Nam urna dolor, lacinia luctus ex sed, ornare luctus eros. Morbi varius est a nisi facilisis, bibendum dictum turpis maximus.';
$comments[1] = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent nec pellentesque velit, ut porta erat. Etiam convallis rhoncus erat vitae sodales. Vivamus porta tellus erat, non congue urna blandit eget. Nam urna dolor, lacinia luctus ex sed, ornare luctus eros. Morbi varius est a nisi facilisis, bibendum dictum turpis maximus.';
$comments[2] = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent nec pellentesque velit, ut porta erat. Etiam convallis rhoncus erat vitae sodales. Vivamus porta tellus erat, non congue urna blandit eget. Nam urna dolor, lacinia luctus ex sed, ornare luctus eros. Morbi varius est a nisi facilisis, bibendum dictum turpis maximus.';
$form = $this->createForm(UserSessionType::class, $userSession, ['choices' => $choices, 'comments' => $comments, 'amounts' => $amounts]);
我的formType如下所示。我捕获注解并将其放入数据属性中
$this->comments = $options['comments'];
$builder
->add('funding', ChoiceType::class, [
'mapped' =>false,
'choices' => $this->choices,
'choice_attr' => function($choiceValue, $key, $index) {
return ['data-comment' => $this->comments[$index]];
},
'expanded' => true
])
然后使用js脚本,我获得数据属性的内容并显示它。
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll('[data-comment]').forEach(function(field) {
var comment = field.getAttribute('data-comment');
var span = document.createElement('div');
span.classList.add("comment");
span.innerHTML = comment;
field.parentNode.appendChild(span);
});
});
谢谢你的洞察力。
1条答案
按热度按时间4c8rllxm1#
是的,您可以直接在formType中执行此操作,无需JavaScript
结果是:
结果为: