symfony2 twig渲染,异常抛出

时间:2012-04-03 00:52:44

标签: symfony twig

所以在我的基本模板中,我有:{% render "EcsCrmBundle:Module:checkClock" %}

然后我创建了ModuleController.php ...

<?php

namespace Ecs\CrmBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Ecs\CrmBundle\Entity\TimeClock;

class ModuleController extends Controller
{
    public function checkClockAction() {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $this->get('security.context')->getToken()->getUser();
        $today = time();
        $start = date('Y-m-d 00:00:00');
        $entities = $em->getRepository('EcsCrmBundle:TimeClock');
        $query = $entities->createQueryBuilder('tc')
                ->select('tc.in1, tc.out1, tc.in2, tc.out2, tc.in3, tc.out3')
                ->where('tc.noteBy = :user')
                ->andWhere('tc.daydate >= :start')
                ->setParameter('user', $user->getid())
                ->setParameter('start', $start)
                ->setMaxResults('1')
                ->getQuery();
         $entities = $query->getSingleResult();
         if (empty($entities)) {
            $ents = "clocked_out";
            $this->get('session')->set('clockedin', 'clocked_out');
         } else {
            for ($i=1; $i <= 3; $i++) {
                if ($entities["in$i"] != NULL) {
                    $ents = "clocked_in";
                    if ($i == 1) {
                        $this->get('session')->set('nextclock', "out$i");
                    } else {
                        $x = $i+1;
                        $this->get('session')->set('nextClock', "out$x");
                    }
                    if ($entities["out$i"] != NULL) {
                        $ents = "clocked_out";
                        $x = $i+1;
                        $this->get('session')->set('nextclock', "in$x");
                    }
                    if ($entities["out3"] != NULL) {
                        $ents = "day_done";
                    }
                }
            }
         }
        return $this->render('EcsCrmBundle:Module:topclock.html.twig', array(
            'cstat' => $ents,
        ));
    }
}

问题是,如果特定用户的特定日期数据库中没有任何内容,我仍然会这样做:

An exception has been thrown during the rendering of a template ("No result was found for query although at least one row was expected.") in ::base.html.twig at line 161.
500 Internal Server Error - Twig_Error_Runtime
1 linked Exception: NoResultException »

我知道这与没有结果的事实有关&#39;来自数据库...但不是我通过if (empty($entities)) {来完成的事情。我无法解决这个问题...任何帮助表示赞赏...

1 个答案:

答案 0 :(得分:19)

替换:

$entities = $query->getSingleResult();

使用

$entity = $query->getOneOrNullResult();

如果查看Doctrine \ ORM \ AbstractQuery,您会看到getSingleResult只需要一个结果。 0将通过异常。

我仔细查看了你的代码,看起来你真的期待一组实体。在这种情况下使用:

$entities = $query->getResult();