Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
730 views
in Technique[技术] by (71.8m points)

html - Symfony Forms: HTML5 datalist

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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';
    }
}

In services.yml:

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

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 %}

Use your field in FormType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('country', DatalistType::class, ['choices' => ['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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...