用户可以拥有包含许多图片的相册,他可以删除图片或上传新图片。我希望这张专辑有1张或更多张图片,但永远不会为空(0)。因此,在用户删除图片之前,我希望能够检查图片的数量是否超过一个,如果小于一个,则显示一个flashbag消息,通知用户他的相册中不能有0张图片。< / p>
这就是我所做的:
/**
* @Security("has_role('ROLE_USER')")
*/
public function avatarUserDeletedAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ApplicationSonataUserBundle:Avatar')->find($id);
if ($this->container->get('security.token_storage')->getToken()->getUser() != $entity->getUser() || !$entity)
return $this->redirect($this->generateUrl('avatarUser'));
$em->remove($entity);
$em->flush();
return $this->redirect($this->generateUrl('avatarUser'));
//return $this->redirectToRoute('avatarUser');
}
ADD:
/**
* @Security("has_role('ROLE_USER')")
*/
public function avatarUserDeletedAction(Request $request,$id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ApplicationSonataUserBundle:Avatar')->find($id);
if ($entity == 1) {
$request->getSession()
->getFlashBag()
->add('success', 'You cannot have less than 1 picture');
} else{
if ($this->container->get('security.token_storage')->getToken()->getUser() != $entity->getUser() || !$entity)
return $this->redirect($this->generateUrl('avatarUser'));
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('avatarUser'));
//return $this->redirectToRoute('avatarUser');
}
我有以下错误:
注意:类Application \ Sonata \ UserBundle \ Entity \ Avatar的对象 无法转换为int
答案 0 :(得分:2)
您需要计算列表$entity
中您实际为$entity
创造条件的项目数量;
你的条件应该在int
上执行$entityCount= count ($entity);
答案 1 :(得分:1)
这个怎么样?
public function avatarUserDeletedAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('ApplicationSonataUserBundle:Avatar')->find($id);
$qb = $em->createQueryBuilder();
$qb->select('count(entity.id)');
$qb->from('ApplicationSonataUserBundle:Avatar','entity');
$count = $qb->getQuery()->getSingleScalarResult();
if ($this->container->get('security.token_storage')->getToken()->getUser() != $entity->getUser() || !$entity)
return $this->redirect($this->generateUrl('avatarUser'));
if($count >= 2) {
$em->remove($entity);
$em->flush();
}
else {
//generate error indicating user that can't have zero elements in the album
}
return $this->redirect($this->generateUrl('avatarUser'));
//return $this->redirectToRoute('avatarUser');
}