1

I'm having trouble solving this problem, when i get in the page for creating a user in my Symfony web app, the user controller complains about the createForm() function and the error only says "Notice: Array to string conversion".

The form is the default created with the crud, actually everything is almost default so I can´t think on a single reason this thing doesn´t work as intended.

I've tried to modify the form to use a multiple selection but that didn´t work either.

And I tried to modify the data type in the entity but that just didn´t even worked because it throwed an error in the file immediately.

Here is the UserType.php (form generator)

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email')
            ->add('roles', ChoiceType::class, [
                'label' => 'Tipo de usuario',
                'attr' => [
                    'multiple' => true,
                    'class'=>'form-control myselect'
                ],
                'choices'  => [
                    'Admin' => 'ROLE_ADMIN',
                    'Usuario' => 'ROLE_USER'
                ],
            
            ])
            ->add('plainPassword', RepeatedType::class, array(
                'type' => PasswordType::class,
                'first_options'  => array('label' => 'Password'),
                'second_options' => array('label' => 'Repeat Password'),
            ))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

The user controller in the breackpoint where Symfony shows the error:

     /**
     * @Route("/new", name="user_new", methods={"GET","POST"})
     */
    public function new(Request $request, UserPasswordEncoderInterface $passwordEncoder): Response
    {
        $user = new User();
        $form = $this->createForm(UserType::class, $user);  // <-- This is the highlighted part.
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

            $user->setPassword(
                $passwordEncoder->encodePassword(
                    $user,
                    $form->get('plainPassword')->getData()
                )
            );

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();

            return $this->redirectToRoute('user_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('user/new.html.twig', [
            'user' => $user,
            'form' => $form->createView(),
        ]);
    }

And the user entity in the fragments where i declare the role variable and the getter and setter:

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


 /**
 * @see UserInterface
 */
public function getRoles(): array
{
    $roles = $this->roles;
    // guarantee every user at least has ROLE_USER
    $roles[] = 'ROLE_USER';

    return array_unique($roles);
}

public function setRoles(array $roles): self
{
    $this->roles = $roles;

    return $this;
}
3
  • Does stackoverflow.com/questions/51744484/… help ? Commented Sep 30, 2021 at 14:15
  • On which line do you get this notice? Commented Sep 30, 2021 at 21:12
  • @nacholibre in the one that says "This is the highlighted part" Commented Oct 7, 2021 at 9:37

1 Answer 1

1

$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];
        }
));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.