Symfony 表单:HTML5 数据列表 [英] Symfony Forms: HTML5 datalist

查看:26
本文介绍了Symfony 表单:HTML5 数据列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用来自数据库(Doctrine)的值来实现 HTML5 数据列表?

How can be implemented HTML5 datalist with values from the database (Doctrine)?

目的:用许多选项替换选择以自动完成输入.

Purpose: replace selects with many options to inputs with autocompletion.

推荐答案

首先,为字段添加新的 FormType:.

First, add your new FormType for the field:.

<?php
// src/Acme/Form/Type/DatalistType
namespace AcmeFormType;

use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormFormInterface;
use SymfonyComponentFormFormView;
use SymfonyComponentOptionsResolverOptionsResolver;

class DatalistType extends AbstractType
{
    public function getParent()
    {
        return TextType::class;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setRequired(['choices']);
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['choices'] = $options['choices'];
    }

    public function getName()
    {
        return 'datalist';
    }
}

services.yml 中:

form.type.datalist_type:
    class: AcmeFormTypeDatalistType
    tags:
        -  { name: form.type, alias: datalist }

你有表单主题吗?如果是,跳到下一步,如果不是,在 app/Resources/views/Form/fields.html.twig 中创建一个新的,并将你的默认 Twig 主题更改为它:

Do you have a form theme? If yes, skip to the next step, if no, create a new one in app/Resources/views/Form/fields.html.twig and change your default Twig theme to it:

# app/config/config.yml
twig:
    form_themes:
        - ':Form:fields.html.twig'

现在为表单主题中的新字段定义模板:

Now define a template for your new field in the form theme:

{% block datalist_widget %}
    <input list="{{ id }}_list" {{ block('widget_attributes') }}{% if value is not empty %}value="{{ value }}"{% endif %}>
    <datalist id="{{ id }}_list">
        {% for choice in choices %}
            <option value="{{ choice }}"></option>
        {% endfor %}
    </datalist>
{% endblock %}

FormType 中使用您的字段:

Use your field in FormType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('country', DatalistType::class, ['choices' => ['a', 'b']]); 
}

而不是 ['a', 'b'] 您需要以某种方式从数据库加载您的选择,我建议将它们作为最简单的解决方案在表单选项中传递.

Instead of ['a', 'b'] You need to load your choices from DB somehow, I'd suggest passing them in form options as the easiest solution.

这篇关于Symfony 表单:HTML5 数据列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆