goulashsoup goulashsoup - 4 months ago 30
PHP Question

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

I have

-method inside the
which should render a form where it should be possible to select a user from a list, press a
-button and then redirects to a route
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

First I copied an example of
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()
->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())];

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

I am sure
gives an array with objects of the class
. 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
can not be called, because
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.


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.