错误:使用Symfony组件表单的ChoiceType调用非对象上的成员函数

时间:2016-08-25 16:41:44

标签: php forms symfony symfony-forms

我在showUsersAction()中有Defaultcontroller - 方法,它应该呈现一个表格,可以从列表中选择用户,按submit - 按钮,然后重定向到路线/showItems/{userId},其中显示了用户的项目。

我知道通过链接可以轻松实现,但我想使用ChoiceType

首先,我从Symfony documentation复制了ChoiceType的示例,但变化很小:

/**
 * @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()));
}

我确信$users给出了一个包含类User对象的数组。当我在浏览器中执行路由时,我收到以下错误消息:

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

第50行是注释行return strtoupper($user->getUsername());

  1. 问题是什么,如何解决?
  2. 在通过提交按钮提交到同一路线后,如何获取所选用户?
  3. 编辑:(因为可能重复) 当然我知道无法调用方法getUsername(),因为$user是一个非对象,它不应该与Symfony文档相关。所以我的问题与Symfony特殊解决方案有关,该解决方案绝对与其他100个错误无关的问题无关。

2 个答案:

答案 0 :(得分:3)

请改用entity类型。这是documentation的链接。它是choice类型的子类型,具有完全相同的功能,并且每个选项都返回一个实体对象。

答案 1 :(得分:0)

由于我在设置entity类型字段时遇到问题,因此我决定在此处发布整个action函数和twig文件的解决方案:

action方法:

/**
 * @Route("/showUsers", name="showUsers")
 */
public function showUsersAction(Request $request){
    // gets array of all users in the database
    $users = $this->getDoctrine()->getManager()->getRepository('AppBundle:User')->findAll();

    $form = $this->createFormBuilder()
    ->setMethod('POST')
    ->add('users', EntityType::class, array(
        'class' => 'AppBundle:User',
        'choices' => $users,

        // This combination of 'expanded' and 'multiple' implements radio buttons
        'expanded' => true,
        'multiple' => false,    
        'choice_label' => function ($user) {
                return $user->__toString();
        }
    ))

    // Adds a submit button to the form. 
    // The 'attr' option adds a class to the html rendered form
    ->add('selected', SubmitType::class, array('label' => 'Show User Items', 'attr' => array('class' => 'button')))
    ->getForm();

    $form->handleRequest($request);

    if ($form->isSubmitted()  && $form->isValid()) {
        // gets the selected user
        $selectedUser = $form["users"]->getData();

        // redirects to route 'showItems' with the id of the selected user
        return $this->redirectToRoute('showItems', array('userId' => $selectedUser->getId()));
    }

    // renders 'default/showUsers.html.twig' with the form as an argument
    return $this->render('default/showUsers.html.twig', array('form' => $form->createView()));
}

twig档案:

{# 
    // app/Resources/views/default/showUsers.html.twig

    Description:
    twig file that implements a form in which one of all users can get
    selected via radio button to show the items of the user after a click
    on the submit button.

    @author goulashsoup

 #}
{% extends 'base.html.twig' %}
{% block title %}Users{% endblock %}
{% block body %}
    <div class="users">
        {{ form_start(form) }}
            {% for user in form.users %}
                {{ form_widget(user) }}
                {{ form_label(user) }}
                <br>
            {% endfor %}
            <br>
        {{ form_end(form) }}
    </div>
{% endblock %}