Reinitialize autocomplete after form submission

314 views Asked by At

I have a custom autocomplete input that is not bound to any entities:

$builder
    ->add('input', TextType::class, [
        'autocomplete' => true,
        'autocomplete_url' => 'https://path-to-autocomplete',
        'tom_select_options' => [
            'create' => false,
            'preload' => true,
            'maxItems' => 1,
            'delimiter' => '/',
        ],
    ])
;

The input correctly requests the autocomplete URL, fetches results, renders the correct item label, and sends the correct item value with the form.

The problem arises after submitting the form at step #6.

  1. Empty form is rendered.
  2. We select an item with ID 15 and label Foo.
  3. Input is rendered correctly.
  4. Form is submitted.
  5. Value of 15 is sent to the server with the form.
  6. Now we have to re-render a form again with an initial value of the input of 15.

At this point, the input value is rendered as 15 instead of Foo. That makes perfect sense. The input just doesn't know how to get a label for an item with ID 15.

enter image description here

Question: how do I provide the input with data about the item label?

I expected the it to have something like reverse_autocomplete_url that would be called after input initialization to get items by their IDs but I don't think there is such an option.

2

There are 2 answers

0
Kolyunya On BEST ANSWER

You have to initialize the form field with options array:

'tom_select_options' => [
    'options' => [
        [
            'value' => 15,
            'text' => 'Foo',
        ],
    ],
],

value and text keys are customizable via valueField and labelField properties.

0
ThomasL On

Considering you used symfony form.

You used $form->isValid() etc..

Persisted and flush your object.

Then instead of re-rendering the twig, call redirectToRoute function to the current route.

If you provide more detail about your usecase i can give you a better answer.