【问题标题】:Undefined variable in Controller控制器中未定义的变量
【发布时间】:2015-01-03 21:57:56
【问题描述】:

我在存储库中有 une dql 查询:

public function TabloBordCmdPeriod($dat1,$dat2)
{$qb = $this->createQueryBuilder('a')
    ->join('a.comElem','c')
    ->select("sum(c.total) as total")
    ->where("a.etat = 'Termine'")
    ->andwhere('a.dateCreation between :dat1 AND :dat2')
    ->setParameters(array('dat1'=>$dat1,'dat2'=>$dat2));
 $query = $qb->getQuery();
$resultats = $query->getSingleScalarResult();
 return $resultats;}

查询运行良好。

我在搜索表单中使用这个查询(没有类的表单),这里是代码表单:

class TBRechPeriodType extends AbstractType {
public function buildForm(FormBuilder $builder, array $options){
$builder
->add('du','date',array('required'=>false,'widget' => 'single_text',  'format' => 'dd-MM-yyyy', 'attr' => array('class' => 'date input-medium')))
->add('au','date',array('required'=>false,'widget' => 'single_text',  'format' => 'dd-MM-yyyy', 'attr' => array('class' => 'date input-medium')))
;
}
public function getName(){
return 'Recherche_Periodique';}
}

在控制器中,代码是:

public function TBAction()
{
    $formTBrech=$this->createForm(new TBRechPeriodType());
    $em = $this->getDoctrine()->getEntityManager();
    if( $request->getMethod() == 'POST')
    {
        $formTBrech->bindRequest($request);
        if( $formTBrech->isValid() )
        {   $data = $formTBrech->getData();
             $period = $em->getRepository('ZXGescodBundle:Commande')->TabloBordCmdPeriod($data['du'],$data['au']);
        }
    }       
      $entities = $em->getRepository('ZXGescodBundle:Commande')->findall();
     return $this->render('ZXGescodBundle:Commande:TB.html.twig', array(
        'formTBrech' => $formTBrech->createView(),
        'period'      => $period,
        ));
}

当我加载模板时,我收到一条错误消息:

Notice: Undefined variable: period in C:\wamp\www\elitetest\src\ZX\GescodBundle\Controller\CommandeController.php line...

如何解决? 提前感谢

【问题讨论】:

  • 'period' => isset($period) ? $period : null

标签: symfony


【解决方案1】:

当它不返回任何结果时

$em->getRepository('ZXGescodBundle:Commande')->TabloBordCmdPeriod($data['du'],$data['au']);

变量 $period 没有赋值。 因此,在分配之前对其进行测试,或者按照 Leggendario 的建议进行操作。

编辑

也许您的表单无效,因此它会跳过为 $period 分配值的部分。

if( $formTBrech->isValid() )
        {  error_log("form is valid"); $data = $formTBrech->getData();
            $period = $em->getRepository('ZXGescodBundle:Commande')->TabloBordCmdPeriod($data['du'],$data['au']);

        return $this->render('ZXGescodBundle:Commande:TB.html.twig', array(
           'formTBrech' => $formTBrech->createView(),
           'period'      => $period,
        ));
    } else {   error_log("form not valid");   ... }

【讨论】:

  • 其实我是通过一个表单动态做一个搜索查询,有两个参数date1和date2,我测试了leggendario所说的$变量period,还是一样的错误。
猜你喜欢
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
  • 1970-01-01
相关资源
最近更新 更多