我需要让简报订阅工作正常。我使用的逻辑是当用户提交他的电子邮件时,我检查是否已经有用户通过电子邮件注册了该用户。如果是,我会检查他是否订阅了时事通讯并进行了相应的订阅。如果电子邮件不在注册用户列表中,那么我有一个匿名用户的新闻稿表。我在这里查看他是否订阅并做了必要的行动。
这是我的控制器操作代码:
/**
* @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来管理用户。这会导致任何问题吗?什么是实施它的最佳方式?
提前致谢!
答案 0 :(得分:2)
听起来您需要授权用户使用您的订阅路线。
在security.yml文件中,添加如下内容:
security:
access_control:
- { path: ^/subscribe, roles: IS_AUTHENTICATED_ANONYMOUSLY }