goulashsoup goulashsoup - 3 months ago 19
PHP Question

Error: Call to a member function on a non-object using ChoiceType of Symfony component form

I have

showUsersAction()
-method inside the
Defaultcontroller
which should render a form where it should be possible to select a user from a list, press a
submit
-button and then redirects to a route
/showItems/{userId}
where the items of a user are shown.

I know that it would be possible to do that easy with a link, but I want to make use of
ChoiceType
:

First I copied an example of
ChoiceType
from the Symfony documentation with a minimal change:

/**
* @Route("/showUsers", name="showUsers")
*/
public function showUsersAction(){
$users = $this->getDoctrine()->getManager()->getRepository('AppBundle:User')->findAll();

$form = $this->createFormBuilder()
->setMethod('POST')
->add('user', ChoiceType::class, [
'choices' => $users,
'choice_label' => function($user) {
/** @var User $user */
return strtoupper($user->getUsername());//here is the problem
},
'choice_attr' => function($user) {
return ['class' => 'user_'.strtolower($user->getUsername())];
},
])
->getForm();

return $this->render('default/showUsers.html.twig',
array('users' => $users, 'form' => $form->createView()));
}


I am sure
$users
gives an array with objects of the class
User
. When I execute the route in the browser I get following error message:

Error: Call to a member function getUsername() on a non-object
in src\AppBundle\Controller\DefaultController.php at line 50


Line 50 is the commented line
return strtoupper($user->getUsername());



  1. What is the problem and how can I solve?

  2. And how can I get the selected User after I submitted via a submit button to the same route?



EDIT: (because of possible duplication)
Of course I know that the method
getUsername()
can not be called, because
$user
is a non-object, which should not be related to the Symfony documentation. So my question relates to a Symfony special solution which has absolutly nothing to do with 100 of other problems where the Error is the same.

Answer

Use entity type instead. Here is a link to documentation. It's a child type of a choice type, with exactly same functionality, and also every option returns an entity object.