Symfony Forms: HTML5 datalist -
how can implemented html5 datalist values database (doctrine)?
purpose: replace selects many options inputs autocompletion.
first, add new formtype 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';     } }   in services.yml:
form.type.datalist_type:     class: acme\form\type\datalisttype     tags:         -  { name: form.type, alias: datalist }   do have form theme? if yes, skip next step, if no, create new 1 in app/resources/views/form/fields.html.twig , change default twig theme it:
# app/config/config.yml twig:     form_themes:         - ':form:fields.html.twig'   now define template new field in form theme:
{% block datalist_widget %}         <input list="{{ id }}" {{ block('widget_attributes') }}>         <datalist id="{{ id }}">             {% choice in choices %}                 <option value="{{ choice }}"></option>             {% endfor %}         </datalist> {% endblock %}   use field in formtype:
public function buildform(formbuilderinterface $builder, array $options) {     $builder->add('country', 'datalist', [choices' => ['a', 'b']]);  }   instead of ['a', 'b'] need load choices db somehow, i'd suggest passing them in form options easiest solution.
Comments
Post a Comment