makinacorpus / autocomplete-bundle

Autocomplete widget and form type for Symfony
2 stars 3 forks source link

Autocomplete API and Symfony widget

This package provides:

Upgrading to 2.x

You have two fixes to make:

Installation

composer require makinacorpus/autocomplete-bundle

Write JavaScript code

You must implement the JavaScript part yourself, all you have to know is that you have two different inputs:

The text input also yield the data-autocomplete-uri which contains a generated URL for querying data (please note that URL can change in time, for security or deduplication reasons). In order to query this URL you can use the following query parameters:

Once you get results, and the user selects a value, you must set the return object id property into the [data-tac-role="id"] element, and the object label property into the [data-tac-role="label"] element.

Bonus point if you empty the hidden value when the users manually edit the text value.

Use a supported JavaScript library

This autocomplete widget needs a third party library to be registered globally in your JavaScript code:

If you use select2 you also need jQuery to be installed (any version).

Register the routing.yml file in your app/routing.yml file:

autocomplete:
    resource: "@AutocompleteBundle/Resources/config/routing.yml"
    prefix: /

And the associated form theme in your app/config.yml file:

twig:
    debug:            "%kernel.debug%"
    strict_variables: false
    form_themes:
        # For select2 based widget:
        - "AutocompleteBundle:Form:fields-select2.html.twig"

Beware that this method is not supported anymore, it might work, it might not.

Usage

First, implement an MakinaCorpus\AutocompleteBundle\Autocomplete\AutocompleteSourceInterface class, that is meant to reflect the business objects in which to autocomplete.

Then just use the MakinaCorpus\AutocompleteBundle\Form\Type\TextAutocompleteType form type in your own form builders, and set the source class name as the source parameter for the form type.