Expected argument of type "string", "object" given at property path

I’m trying to change a password of a user. The user is selected in a dropdownlist.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('password', PasswordType::class, array('label' => 'Password'))
        ->add('reset', SubmitType::class, array('label' => 'Reset'))
        ->add('username', EntityType::class, array('class' => User::class,
            'query_builder' => function (EntityRepository $er) {return $er->createQueryBuilder('u')->orderBy('u.username', 'ASC');
            },'choice_label'=>'username', 'label'=>'User'));

}

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

When the form is first rendered, i see the list of users. Then i fill in the new password en submit.
And then i get the error:
“Expected argument of type “string”, “object” given at property path username”. The error occures in the controller in line

$form->handleRequest($request);

This is the controller:

    $form = $this->createForm(ResetPwdType::class, new User());

    $form->handleRequest($request);

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

            $u = $form->get('username')->getData();
            $user = $this->getDoctrine()->getManager()->getRepository(User::class)->findOneBy(['username' => $u->getUsername()]);

            $newPwd = $passwordEncoder->encodePassword($user, $form->get('password')->getData());
            $user->setPassword($newPwd);

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();
            $this->addFlash('success', 'Password reset!');
            $params = null;
            return $this->redirectToRoute('reset_pwd');


        }


    return $this->render(
        'security/resetpwd.html.twig',array('form' => $form->createView()));

I’m think there is a property that needs to be a string in stead of an object. And that is just has got someting to do with the username property.
I’ve tried to add a toString methode on the User Entity without success.
What must i change to get ride of the error and save the new password to the db.

Source: Symfony Questions

Was this helpful?

1 / 0

Leave a Reply 1

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


hamed

hamed

hello,
the reason for this error is query build,
you must use entity::class

“`
$builder->add(‘name’, EntityType::class, [
‘class’ => Product::class,
// ‘label’ =>’Products’,
‘mapped’ => false,
// ‘choice_name’ => ‘name’,
‘choice_label’=> function(Product $product = null){
if($product)
return $product->getName();
},
‘choice_value’ => function(Product $product = null){
if($product)
return $product->getId();
},
// ‘attr’ => [‘class’ => ‘col-lg-8’] ,
‘label_attr’ => [‘style’=>’text-align:right’]
] );
“`