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;
}