[英]Notification dropdown symfony
我有一個通知圖標。 當用戶點擊它時,會出現一個下拉列表並顯示一個列表。 我想過濾列表以僅顯示與連接用戶相關的內容。
{% if app.user.roles[0] == "ROLE_DEVELOPPER"%}
<!-- dropdown notification message -->
<li class="dropdown">
<a title="Notifications" href="#fakelink" class="dropdown-toggle" data-toggle="dropdown">
<strong> <i class="fa fa-bell"></i></strong>
</a>
{% if notif_conges|length > 0 %}
<ul class="dropdown-menu animated half flipInX">
//this section
{% for notif_c in notif_conges %}
{% if notif_c.etat == "Acceptée" %}
<li><a>Votre demande : "{{notif_c.motif}}" Envoyée le "{{notif_c.CreatedAt|date('Y-m-d H:i:s')}}" a était traitée </a></li>
{% endif %}
{% endfor %}
</ul>
{% endif %}
</li>
{% endif %}
喲必須使用is_granted twig過濾器。
您可以指定一個用戶角色,但是為所有登錄的用戶指定了IS_AUTHENTICATED_REMEMBERED角色。
{% is_granted('IS_AUTHENTICATED_REMEMBERED') %}
<!-- dropdown notification message -->
...
{% endif %}
您想要過濾通知。 只需顯示有關已連接用戶的通知。 你有兩個解決方案:
(非常)糟糕的方式:在視圖中添加測試
<ul class="dropdown-menu animated half flipInX">
//this section
{% for notif_c in notif_conges %}
{% if notif_c.etat == "Acceptée" and notif_c.user = app.user %}
<li><a>Votre demande : "{{notif_c.motif}}" Envoyée le "{{notif_c.CreatedAt|date('Y-m-d H:i:s')}}" a était traitée </a></li>
{% endif %}
{% endfor %}
</ul>
這是一種糟糕的方式,因為您將所有通知轉發到視圖
糟糕的方法:在控制器中添加一個過濾器
class YourController
{
public yourAction()
{
/** ... your code to handle notifications **/
foreach ($notifications as $notification) {
if ($notification->getUser()->getId() == $this->getUser()->getId)) {
$filteredNotification[] = $notification;
}
}
return $this->render('your_template_file', [
'notif_c' => $filteredNotifications
]);
}
}
這仍然是一種糟糕的方式,因為您正在從數據庫中檢索所有通知。
好方法:只詢問必需品通知您的存儲庫假設您的通知是使用Doctrine進行檢索,存儲庫可以過濾數據以僅檢索相關數據。
class YourController
{
public yourAction()
{
/** ... your code is certainly something lke this: **/
$notificationRepository = $this->entityManager->getRepository('AppBundle:Notification');
$notifications = $notificationRepository->findAll();
render
return $this->render('your_template_file', [
'notif_c' => $notifications
]);
}
}
用findBy(array $criteria)
替換findAll()
並添加一個條件作為第一個參數:
class YourController
{
public yourAction()
{
$notificationRepository = $this->entityManager->getRepository('AppBundle:Notification');
$notifications = $notificationRepository->findBy([
'etat' => 'Acceptée',
'user' => $this->getUser(), //this could be a little different, I do not remember how to handle user in Sf2.8
]);
render
return $this->render('your_template_file', [
'notif_c' => $notifications
]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.