2012-04-10 78 views
1

我需要訂閱訂閱電子報。我使用的邏輯是用戶提交他的電子郵件時,我檢查是否已有用戶通過電子郵件註冊到該網站。如果是的話,我會檢查他是否訂閱了新聞稿並做適當的訂閱。如果電子郵件不在註冊用戶列表中,那麼我有一個匿名用戶的時事通訊表。我在這裏檢查他是否被認購,並採取必要的行動。Symfony2:訂閱電子報

這裏是我的控制器動作代碼:

/** 
* @Route("/newsletter/", name="site_newsletter") 
* @return array 
*/ 
public function newsletterSubscriptionAction(httpRequest $request) 
{ 
    $email = $request->request->get('email'); 

    try { 

     $email = $request->request->get('email'); 
     $em = $this->getDoctrine()->getEntityManager(); 
     $query = $em->createQuery(
      'SELECT u FROM MyBundle:User u WHERE u.email = :email' 
     )->setParameter('email', $email); 

     $user = $query->getSingleResult(); 

     if(!is_object($user)){ //this means anonymous user not registered to site 
      $em = $this->getDoctrine()->getEntityManager(); 
      $query = $em->createQuery(
       'SELECT n FROM MyBundle:Newsletter n WHERE n.email = :email AND n.isSubscribed = 1' 
      )->setParameter('email', $email); 

      $record = $query->getSingleResult(); 

      if($record){ 
       $msg = "You are already subscribed!"; 
      }else{ 
       $newsletter = new Newsletter(); 
       $newsletter->setEmail($email); 
       $newsletter->setIsSubscribed(true); 

       $em = $this->getDoctrine()->getEntityManager(); 
       $em->persist($newsletter); 
       $em->flush(); 

       $msg = "You have been subscribed to our newsletter! Thank You."; 
      } 
     }else{ 
      if($user->getNewsletterSubscription()){ 
       $msg = "You are already subscribed!"; 
      }else{ 
       $user->setNewsletterSubscription(1); 
       $em = $this->getDoctrine()->getEntityManager(); 
       $em->flush();      
       $msg = "You have been subscribed to our newsletter! Thank You."; 
      }     
     } 

    } 
    catch (\Exception $e) { 
     $msg = 'Some problem occured. Please try again later'; 
    } 

    if ($this->getRequest()->isXmlHttpRequest()) { 
     return new \Symfony\Component\HttpFoundation\Response($msg); 
     return array('msg' => $msg); 
    } 

} 

我使用AJAX調用這個控制器動作。這不起作用。回到ajax的數據是重定向的登錄頁面。

我使用FOSUSerBundle來管理用戶。這是否導致任何問題?什麼是實現它的最佳方式?

在此先感謝!

回答

2

這聽起來像你需要給匿名用戶許可使用你的訂閱路線。

在你security.yml文件,添加類似:

security: 
    access_control: 
     - { path: ^/subscribe, roles: IS_AUTHENTICATED_ANONYMOUSLY } 
+0

謝謝!有效。 – VishwaKumar 2012-04-11 04:02:28

+0

嘿。推動我超過2000代表。謝謝。 – Cerad 2012-04-11 12:47:25