- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
简短的长问题,在对此进行了大量研究并找到了很多关于如何扩展现有字段类型、继承它们或更改后端某些内容的信息之后,但对于前端的实际渲染绝对没有,我是来问这个问题的。
手头“问题”的简短解释:我需要一个 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/
我想显示 已检查 如果一个变量为空所以我做了这个代码 {{ form_widget(form.showPrice, {% if travel is null %} {'attr': {'checke
我去看看 Symfony 的扩展 Twig 函数 form_widget 实际是如何工作的。我期待在 symfony / src / Symfony / Bridge / Twig / Extensi
是否可以对表单元素属性使用原始过滤器?我想要这样的东西: {{ form_widget(searchForm.query, { 'type': 'search', 'attr': {
在 Controller 端使用 PHP,我可以使用 createFormBuilder() 将占位符添加到我的字段: $form = $this->createFormBuilder($compan
我想替换: {{ form_errors(form.name) }} {{ form_widget(form.name, { 'attr': {'placeholder': 'Nom'} }) }}
在调用 form_widget() 时,我想用 Twig 将类添加到现有类中。 -function,所以我想合并它们。但是当我使用 {{ form_widget(form.field1), {'att
简短的长问题,在对此进行了大量研究并找到了很多关于如何扩展现有字段类型、继承它们或更改后端某些内容的信息之后,但对于前端的实际渲染绝对没有,我是来问这个问题的。 手头“问题”的简短解释:我需要一个 E
如何自定义以下代码?我要使用来自数据库的复选框。 这是我的表单 $builder->add('entityname', 'entity', array( 'class'
为了验证表单,我使用了一个标准: {{ form_widget(form.save, {'attr': {'class': 'btn btn-sm btn-danger'}, 'label': 'Su
我一直在关注以下资源中的文档 http://silex.sensiolabs.org/doc/providers/form.html 但我收到以下错误 Twig_Error_Syntax: The f
当我在 Controller 中创建一个表单时,如下所示: $form = $this->createFormBuilder() ->add('field_name') ->getFo
我是一名优秀的程序员,十分优秀!