I've been trying to create a DataList in my Symfony application by following this thread. However, the custom template is never loaded, I just get a textfield and no responses when I attempt to search for strings in the list.
Below is my modified code of the linked thread above:
My src/Form/DataListType class:
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class DataListType extends AbstractType
{
public function getParent()
{
// return EntityType::class;
return TextType::class;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setRequired(['choices']);
}
public function getName() {
return 'datalist';
}
}
templates\form\datalist.html.twig:
{% block datalist_widget %}
<div class="form-group">
<input {{ block("widget_attributes") }} list="{{ id }}_list" class="form-control" />
<datalist id="{{ id }}_list">
{% for choice in form.vars.choices %}
<option value="{{ choice.value }}">{{ choice.label }}</option>
{% endfor %}
</datalist>
</div>
{% endblock %}
My config/packages/twig.yml
twig:
default_path: '%kernel.project_dir%/templates'
form_themes:
- '@FOSCKEditor/Form/ckeditor_widget.html.twig'
- 'form/datalist.html.twig'
globals:
sourceFiles: '@App\Service\SourceFile'
when@test:
twig:
strict_variables: true
The config/services.yml is as follows:
parameters:
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/'
exclude:
- '../src/DependencyInjection/'
- '../src/Entity/'
- '../src/Kernel.php'
- '../src/Tests/'
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
form.datalist_type:
class: Acme\Form\DataListType
tags:
- { name: form, alias: datalist }
I then add the datalist to the form in a controller by doing the following:
...
$builder->add('test', DataListType::class, [
'choices' => ['one', 'two', 'three']
]);
...
As I mentioned above, the custom Twig template never loads and I just get a textfield.