Search code examples
phpsymfonyformbuilder

Illegal characters in $child param of FormBuilderInterface->add() method


I am trying to create a form that will change the user roles, for a lot of users on one page. Users have unique email and id. However, when I try to add the $child parameter to the form that contains the user's email:

$form->add($user->getEmail(), ChoiceType::class, [
                'choices' => $options,
                'placeholder' => 'Select role',
                'data' => $defaultValue,
            ]);

...I get an error:

The name "mail@example.com" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":").

This problem disappears if I add a username instead of an email:

$form->add($user->getUsername(), ChoiceType::class, [
                'choices' => $options,
                'placeholder' => 'Select role',
                'data' => $defaultValue,
            ]);

...but the same usernames can be a great many.

How can I pass a user's email or user id to the form to make sure that the value of the selected role is relevant to a particular user?


Solution

  • I found a solution. I passed the user id value to the $child parameter, and replaced it in the client side using the "label" option.

    $form->add($user->getId(), ChoiceType::class, [
                    'choices' => $options,
                    'placeholder' => 'Select role',
                    'data' => $defaultValue,
                    'label' => $user->getEmail(),
                ]);
    

    So I have a beautiful returned array that looks like:

    ['1' => 'role1',
     '2' => 'role2',
     '3' => 'role3',]
    

    However, on the client side everything remains clear, since the ids have been replaced by the users' emails.