Symfony表单:HTML5 datalist [英] Symfony Forms: HTML5 datalist

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

问题描述

如何使用数据库中的值(Doctrine)实现HTML5 datalist?

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 Acme\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class DatalistType extends AbstractType
{
    public function getParent()
    {
        return 'text';
    }

    public function setDefaultOptions(OptionsResolverInterface $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: Acme\Form\Type\DatalistType
    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') }}>
        <datalist id="{{ id }}_list">
            {% for choice in choices %}
                <option value="{{ choice }}"></option>
            {% endfor %}
        </datalist>
{% endblock %}

使用 FormType <中的字段/ code>:

Use your field in FormType:

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

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

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 datalist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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