php - Symfony 5 - Notice: Array to string conversion in user create form because of roles

one text

Solution:

$roles is an array, you can see it in your configuration :

 /**
 * @ORM\Column(type="json")
 */
 private $roles = [];

Even if we have type="json", it will be used as an array but in your database it will be a regular json.

ChoiceType here is a string so you can't use it in $roles.

You can add a data transformer (see similar response) to convert the value when displaying it in your select or when using it with your entity.

The simple way to do it is using a CallBackTransformer directly in your form type :

use Symfony\Component\Form\CallbackTransformer;

$builder->get('roles')
    ->addModelTransformer(new CallbackTransformer(
        fn ($rolesAsArray) => count($rolesAsArray) ? $rolesAsArray[0]: null,
        fn ($rolesAsString) => [$rolesAsString]
));

Or if your are not using PHP 7.4+

$builder->get('roles')
    ->addModelTransformer(new CallbackTransformer(
        function ($rolesAsArray) {
             return count($rolesAsArray) ? $rolesAsArray[0]: null;
        },
        function ($rolesAsString) {
             return [$rolesAsString];
        }
));

Source