Symfony2 - 要求为参数提供值

时间:2018-02-11 14:54:06

标签: php symfony model-view-controller controller routing

尝试使用FOSuserbundle中自定义ProfileController的方法editAction()时,会返回以下异常:

  

控制器“UserBundle \ Controller \ ProfileController :: editAction()”要求您为“$ id”参数提供一个值(因为没有默认值,或者因为在此之后存在非可选参数)。 / p>

UserBundle \控制器\ ProfileController可:: editAction():

/**
 * Edit the user
 */
public function editAction($id)
{
    //die('ok');
    //$user = $this->getUser();

    //$id = $request->query->get('id');

    $user = $this
        ->getDoctrine()
        ->getManager()
        ->getRepository('UserBundle:User')
        ->find($id)
    ;

    if (!is_object($user) || !($user instanceof UserInterface)) {
        throw new AccessDeniedException('This user does not have access to this section.');
    }

    /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);

    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }

    /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    //$formFactory = $this->get('fos_user.profile.form.factory');

    //$form = $formFactory->createForm();

    $form = $this->createForm(new RegistrationEditFormType(), $user);
    //$form->setData($user);

    $form->handleRequest($request);

    if ($form->isValid()) {

        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');


        // Updating the user
        $userManager->updateUser($user);

        $event = new FormEvent($form, $request);
        $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

        //$userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('lld_profile_show');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }
    $request->getSession()->getFlashBag()->add('info-edit', 'Your account has been updated!');
    return $this->render('UserBundle:Profile:edit.html.twig', array(
        'form' => $form->createView(),
        'user' => $user
    ));
}
来自admin.html.twig的

代码段:

<tbody>
                                {% for user in users %}
                                    <tr class="">
                                        <td>{{ user.id }}</td>
                                        <td>{{ user.firstName }}</td>
                                        <td>{{ user.lastName }}</td>
                                        <td>{{ user.amount }}</td>
                                        <td>
                                            {% if user.isAccountNonLocked %}
                                                <span class="label label-success">Enabled</span>
                                            {% else %}
                                                <span class="label label-default">Disabled</span>
                                            {% endif %}
                                        </td>
                                        {#

                                        <td>
                                            {% if user.image %}
                                                <img src="{{ asset(user.image.uploadDir ~ '/' ~ user.image.id ~ '.' ~ user.image.url) }}" style="max-width: 130px;max-height: 130px;" />
                                            {% endif %}

                                        </td>

                                        #}

                                        <td>{{ user.date|date('m-d-Y   H:i:s') }}</td>
                                        <td>{{ user.updatedAt|date('m-d-Y   H:i:s') }}</td>
                                        <td></td>
                                        <td><a href="{{ path('lld_user_delete', {'id': user.id}) }}" class="label label-danger">Delete</a> <a href="{{ path('lld_user_deactivate', {'id': user.id}) }}" class="label label-default">Disable</a> <a href="{{ path('lld_user_activate', {'id': user.id}) }}" class="label label-success">Enable</a> <a href="{{ path('fos_user_profile_edit', {'id':user.id}) }}" class="label label-primary">Edit</a> </td>
                                    </tr>
                                {% endfor %}
                                </tbody>

正在使用的具体行:

 <td><a href="{{ path('lld_user_delete', {'id': user.id}) }}" class="label label-danger">Delete</a> <a href="{{ path('lld_user_deactivate', {'id': user.id}) }}" class="label label-default">Disable</a> <a href="{{ path('lld_user_activate', {'id': user.id}) }}" class="label label-success">Enable</a> <a href="{{ path('fos_user_profile_edit', {'id':user.id}) }}" class="label label-primary">Edit</a> </td>

adminAction():

public function adminAction()
{
    $user = $this->getUser();
    if (!$this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') || !$this->container->get('security.context')->isGranted('ROLE_ADMIN') || !$this->container->get('security.context')->isGranted('ROLE_MANUFACTURER')) {
        return $this->redirect($this->generateUrl('fos_user_security_login'));
    }

    /*
     $userManager = $this->container->get('fos_user.user_manager');
     Changing the role of the user
    $user->addRole('ROLE_ADMIN');
     Updating the user
    $userManager->updateUser($user);

    var_dump($user);exit;
     */

    $userManager = $this->container->get('fos_user.user_manager');

    $users = $userManager->findUsers();

    return $this->render('UserBundle:Admin:admin.html.twig', array(
        'users' => $users
    ));
}

public function deleteAction(Request $request, $id)
{
    if (!$this->container->get('security.context')->isGranted('ROLE_ADMIN')) {
        return $this->redirect($this->generateUrl('fos_user_security_login'));
    }

    $userManager = $this->container->get('fos_user.user_manager');
    $user = $userManager->findUserBy(array('id' => $id));

    if(null === $user)
    {
        throw new NotFoundHttpException("User with id ".$id." doesn't exist.");
    }

    $userManager->deleteUser($user);
    $request->getSession()->getFlashBag()->add('info-delete', 'The user '.strtoupper($user->getCompanyName()).' has been deleted successfully!');
    return $this->redirect($this->generateUrl('admin'));

}

所以,我陷入了困境,我没有看到这个问题的来源,因为从逻辑上从正在进行点击的行中检索到了这个参数。显然正在调用正确的动作(自定义editAction())。

有什么我想念的吗?有什么建议吗?我试过检查类似的帖子,但没有人可以帮助我。

enter image description here

1 个答案:

答案 0 :(得分:1)

原因是您正在使用本机FOS路由,它根本没有id参数。

<route id="fos_user_profile_show" path="/" methods="GET">
    <default key="_controller">fos_user.profile.controller:showAction</default>
</route>

这是一个个人资料编辑页面,可让您编辑自己的个人资料,因此必须从会话中获取ID。

如果您尝试提供某种CRUD功能,则必须切换到即用型数据网格/管理系统(例如SonataUserBundle)或编写自定义路由和控制器。