Symfony Forms: HTML5 datalist

前端 未结 4 1928
甜味超标
甜味超标 2020-12-06 14:41

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

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

4条回答
  •  情书的邮戳
    2020-12-06 15:09

    I spent some time trying to solve this issue, and there is a quite simple solution which solves Konstantin's issue with database access. It is to create a new form type which has EntityType as it's parent.

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

    You can then create a new template for this widget:

    {# views/form/fields.html.twig #}
    {% block datalist_widget %}
        
        
            {% for choice in choices %}
                
            {% endfor %}
        
    {% endblock %}
    

    Finally, in the buildForm function of the form you are building, you can add your form element using the DatalistType, and using the EntityType options.

    $builder->add('fieldName', DatalistType::class ,
            array('required' => false, 
                  'label' => 'fieldLabel', 
                  'class' => 'AppBundle\Entity\EntityName',
                  'choice_label' => 'entityField'))
    

提交回复
热议问题