gpt4 book ai didi

javascript - Symfony - 自定义 FieldType form_widget 渲染

转载 作者:行者123 更新时间:2023-11-29 20:42:18 24 4
gpt4 key购买 nike

简短的长问题,在对此进行了大量研究并找到了很多关于如何扩展现有字段类型、继承它们或更改后端某些内容的信息之后,但对于前端的实际渲染绝对没有,我是来问这个问题的。

手头“问题”的简短解释:我需要一个 EntityType 字段(ChoiceType - HTML Select)来使用我自己的过滤逻辑并动态地从 ajax 调用中提取结果,立即替换下拉列表中列出的选项。

当前代码(有效):在 FormType.php 中

//in buildForm
{
$builder->add('trainer', EntityType::class, [
'class' => Trainer::class,
'choices' => $training->trainer_list ?? [],
'label' => 'seminar.trainer.form.trainer.label',
'placeholder' => 'form.trainer.placeholder',
'required' => false,
'attr' => ['class' => 'trainer2select'] // has no outcome whatsoever?!
])
$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'onPreSubmit']);
}

function onPreSubmit(FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();

$trainer = $this->em->getRepository(Trainer::class)->find($data['trainer']);

$form->add('trainer', EntityType::class, [
'class' => Trainer::class,
'data' => $trainer,
'label' => 'seminar.trainer.form.trainer.label',
'placeholder' => 'form.trainer.placeholder',
'required' => false,
]);
}

在 Twig 上:

{% if field == 'trainer' %}
{{ form_row(attribute(form, field), {'id': 'trainer'}) }}
{% else %}
{{ form_row(attribute(form, field)) }}
{% endif %}

{% block javascripts %}
<script>
var lastTime;
var timeoutEvents = [];
$(document).ready(() => {
function trainer_changed() {
let input = event.target;
lastTime = Date.now();

timeoutEvents.push(setTimeout(() => {
if (Date.now() - lastTime < 150)
return;
jQuery.ajax({
url: '{{ path('trainer_select_ajax') }}',
type: 'GET',
data: {
search: input.value,
start: {{ seminar.event.start.date | date('Y-m-d') }},
end: {{ seminar.event.end.date | date('Y-m-d') }}
},
success: function (trainers) {
let trainer = $('#trainer');
trainer.get(0).options.length = 1; // reset all options, except for the default
trainers.forEach(tr => {
trainer.append(new Option(tr.text, tr.id));
});
let search = $($("input.select2-search__field").get(1));
if (search.get(0)) {
search.get(0).oninput = null; // detach our event handler so we don't loop
search.trigger('input'); // rebuild the dropdown choices
search.get(0).oninput = trainer_changed; // reattach our event handler
}
}
});
lastTime = Date.now();
timeoutEvents.forEach(e => {
clearTimeout(e);
});
}, 200));
}
function select_opened() {
let trainerinput = $('input.select2-search__field').get(1);
if (trainerinput) {
trainerinput.oninput = trainer_changed;
}
}
$('#select2-trainer-container').click(select_opened);
});
</script>
{% endblock %}

因此,显然 EntityType 字段是使用 select2 扩展呈现的。我显然可以用 javascript 替换功能,但我只想定义我自己的“AjaxEntityType”,让 form_widget 按我的意愿呈现。我可以在多个项目中使用的东西,而无需使用一些愚蠢的技巧,例如提供默认类名和调用 javascript 在全局页面加载后更改呈现。那么……怎么办?

我检查过的资源已被证明对我想要实现的目标毫无值(value):https://symfony.com/doc/current/form/form_customization.html , https://symfony.com/doc/current/form/form_themes.html还有更多。

编辑澄清:我正在寻找的最佳情况是自定义 FieldType 的简约示例,该示例始终呈现为 <select id="FieldTypeWidget"> ,将始终调用 $('#FieldTypeWidget').select2({ajax: {foo}, searchFunction: {bar}});

https://github.com/tetranz/select2entity-bundle我可以找到一个示例来说明如何在 bundle 中提供此功能,但是在我的应用程序中是否有更简单的方法?

最佳答案

我会说你正在看的是 this Symfony documentation page 中解释的内容

这是他们的示例,根据您的需要进行了一些修改:

src/Form/Type/AjaxEntityType.php

<?php

namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EntityType;

class AjaxEntityType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
/**
* This is the default of your field,
* add or remove based on your needs,
* your goal, is to only keep sensible defaults
* that you want on every single objects of this class
*/
'required' => false,
]);
}

public function getParent()
{
return EntityType::class;
}
}

这里是“魔法”发生的地方:
当你的类被称为 WhateverNameType 时,Symfony 只会删除它的 Type 部分并对其进行规范化(简化为 lcfirst 它)。
所以 WhateverNameType 将以 whateverName 结尾。
然后,您只需要知道在呈现 form_widget 中调用表单元素以结束正确的命名 block :whateverName_widget

templates/form/fields.html.twig

{% use 'form_div_layout.html.twig' %}

{% block ajaxEntity_widget %}
{{ parent() }}
<script>
$('#{{ form.vars.id }}').select2({ajax: {foo}, searchFunction: {bar}});
</script>
{% endblock %}

另请注意文档页面中的便捷提示:

You can further customize the template used to render each children of the choice type. The block to override in that case is named "block name" + entry + "element name" (label, errors or widget) (e.g. to customize the labels of the children of the Shipping widget you'd need to define {% block shipping_entry_label %} ... {% endblock %}).

还请记住,如稍后在同一页上所述,您的表单模板覆盖必须正确注册:

config/packages/twig.yaml

twig:
form_themes:
- 'form/fields.html.twig'
# you might have this configuration already,
# for example, if you use bootstrap theming.
# If so, just copy the configured template path stated here
# in the 'use' statement of the file form/fields.html.twig

然后直接使用它:

$builder->add('trainer', AjaxEntityType::class, [ class => Trainer::class, ]);

也值得一读:

关于javascript - Symfony - 自定义 FieldType form_widget 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55130038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com