2013-07-12 28 views
0

我是Symfony的新手(正在處理我的第一個項目!),我想將用戶發回登錄頁面,並提示「您未登錄」噸。重定向發送變量symfony

有沒有辦法運行的東西,使得它/固定/登錄改變用戶的URL和發送數據完全一樣:

return $this->render('radloginBundle:Default:login.html.twig',array('errors'=>'You aren\'t logged in'));

因此,在login.html.twig,我有:

{% if errors is defined %} 
<div class="red">{{errors}}</div> 
{% endif %} 

它會向用戶顯示錯誤消息?

我聽說過一個方法,你可以這樣做的:

return $this->redirect($this->generateUrl('radlogin_login',array('errors'=>'You aren\'t logged in'))); 

,但用戶的鏈接變爲:代替

http://.../app_dev.php/login 
+1

設置一個Flash消息並拋出一個AccessDeniedException –

回答

1

你可以使用會話服務的Flash包通過單個請求傳遞值(實際上是重定向)。

關於flash messages can be found in the Symfony documentation的章節。

如果文檔是不夠的,這裏是一個代碼示例:

public function updateAction() 
{ 
    // if the method returns null, the user isn't logged in 
    if ($this->getUser() === null) { 
     $this->get('session')->getFlashBag()->add(
      'errors', // this is a key 
      'You are not logged in' // this is a value to add to key 
     ); 

     // this will redirect to the login page if the user isn't logged in 
     throw new \Symfony\Component\Security\Core\Exception\AccessDeniedException(); 
    } 
} 

然後你可以使用的方法的文檔中的說明顯示錯誤。