Smart Form Controls

Ajax-Powered Autocomplete <select>

Breathe life into EntityType and ChoiceType fields with Tom Select and a sprinkle of Ajax.

composer require symfony/ux-autocomplete
// ... use statements hidden - click to show
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class TimeForAMealForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('foods', FoodAutocompleteField::class)
            ->add('name', TextType::class, [
                'label' => 'What should we call this meal?',
            ])
        ;
    }
}
// ... use statements hidden - click to show
use App\Entity\Food;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Count;
use Symfony\UX\Autocomplete\Form\AsEntityAutocompleteField;
use Symfony\UX\Autocomplete\Form\BaseEntityAutocompleteType;

#[AsEntityAutocompleteField]
class FoodAutocompleteField extends AbstractType
{
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'class' => Food::class,
            'searchable_fields' => ['name'],
            'label' => 'What sounds tasty?',
            'choice_label' => 'name',
            'multiple' => true,
            'constraints' => [
                new Count(min: 1, minMessage: 'We need to eat *something*'),
            ],
            // 'security' => 'ROLE_SOMETHING',
        ]);
    }

    public function getParent(): string
    {
        return BaseEntityAutocompleteType::class;
    }
}
Symfony logo

UX Autocomplete

Install It

$ composer require symfony/ux-autocomplete