2014-11-21 62 views
2

我有我的控制器内的两个简单的功能:Symfony的2调用一个函数(temlate渲染)在控制器

public function indexAction(){ 

    $userid = $this->getUser()->getId(); 

    $userdata = $this->getDoctrine() 
      ->getRepository('LiveupUserBundle:userData') 
      ->findOneById($userid); 

    $userfriends = $this->getDoctrine() 
      ->getRepository('LiveupUserBundle:userFriends') 
      ->findByUser($userid); 
    return $this->render('LiveupMainBundle:Main:profile.html.twig', array(
     'userdata' => $userdata, 
     'userfriends' => $userfriends 
    )); 
} 

public function peopleAction($nick){ 
    if($nick){ 

     $frienddata = $this->getDoctrine() 
       ->getRepository('LiveupUserBundle:userData') 
       ->findOneByNick($nick); 

     if($frienddata->getId() === $this->getUser()->getId()) 
     { 
      self::indexAction(); 
     }else{ 
      $friendfriends = $this->getDoctrine() 
        ->getRepository('LiveupUserBundle:userFriends') 
        ->findByUser($frienddata->getId()); 

      return $this->render('LiveupMainBundle:Main:people_profile.html.twig', array(
       'frienddata' => $frienddata, 
       'friendfriends' => $friendfriends 
      )); 
     } 
    } 
} 

问题是,如果在第二个函数声明是真实的,当,我想执行indexAction并从该函数(profile.html.twig)呈现模板,但我没有得到任何响应错误。谁能帮我? 在此先感谢。

回答

1

我认为你要找的是forwarding a request。从文档,你可以做这样的事情:

public function peopleAction($nick){ 
    if($nick){ 

     $frienddata = $this->getDoctrine() 
      ->getRepository('LiveupUserBundle:userData') 
      ->findOneByNick($nick); 

     if($frienddata->getId() === $this->getUser()->getId()) 
     { 
      $response = $this->forward('AppBundle:Something:index', array(
       'var1' => $anyVar //if you need to forward a param 
      )); 
     }else{ 
      $friendfriends = $this->getDoctrine() 
       ->getRepository('LiveupUserBundle:userFriends') 
       ->findByUser($frienddata->getId()); 

      $response = $this->render('LiveupMainBundle:Main:people_profile.html.twig', array(
       'frienddata' => $frienddata, 
       'friendfriends' => $friendfriends 
      )); 
     } 

     return $response; 
    } 
} 

此外,通过看你的代码,您还是会你$nick变量计算false因为没有响应将返回得到一个错误。你应该确保你总是返回一个控制器的回应。

另一件要考虑的事情,也许重定向也将满足您的需求。看看the docs来看看怎么做,从控制器来看非常简单。

+0

请问,在你的行动结束时,有一个'return'而不是两个的事实是编程中所谓的'重构'?无论如何,感谢解决方案,非常有趣 – 2014-11-21 19:57:00

0

你忘了return声明:

return self::indexAction(); 

此外,如果nick可以是空的,你应该处理这种情况下,并抛出一个异常,或者返回的响应。