Select2 selected choices not available in getData on Symfony 5

Im having a select2 choicetype field in my form which is using ajax to retrieve choices from an API. It is part of a symfony form. The field is configured like this:

->add('places',
    ChoiceType::class,
    [
        'multiple'    => true,
        'label'       => $this->t->trans('places'),
        'attr'        => ['class' => 'select2-multiple'],
        'label_attr'  => ['class' => 'control-label'],
        'help'        => $this->t->trans('create_new_announcement_places_help'),
        'constraints' => [new NotBlank(['message' => 'field_empty'])],
        'required'    => true,
    ])

The javascript which is enabling the select2 properties looks like this and it works properly.

$("#create_places").select2({
  ajax: {
    url: GLOBALS.publicApi + "/geocode/city?token=" + GLOBALS.clientToken,
    dataType: 'json'
    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
  },
  minimumInputLength: 3
});

On the server side the form is handled like this:

public function create($projectId, Request $request)
{
    $project    = $this->getProject($projectId);
    $createForm = $this->createForm(CreateType::class);

    $createForm->handleRequest($request);
    if ($createForm->isSubmitted() && $createForm->isValid()) {
        $this->handleCreateFormRequest($createForm, $projectId);
    } elseif ($createForm->isSubmitted() && !$createForm->isValid()) {
        dump($createForm->getData());
        dump($_POST);
        $this->addFlash('danger', $this->trans('create_announcement_wizard_error'));
    }

    return $this->render('client/announcements/create.html.twig', ['createForm' => $createForm->createView(), 'project' => $project]);
}

However the $createForm->getData() does have all other field values but not the select2 choices which are selected be the user. But in the native $_POST array the selected choices do exist.
It works well when using static options instead of remote data for the select2 field.
Also the symfony form validation fails which is the logical behavior in this case.

Select2 Version: 4.0.13
Symfony Version: 5

Does anyone know how to fix this.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *