【问题标题】:Symfony2 Impossible to access an attribute on a NULL variable with sessionsSymfony2 无法通过会话访问 NULL 变量的属性
【发布时间】:2015-04-20 12:21:23
【问题描述】:

正如我的标题所说,我收到了错误,但我无法弄清楚为什么我的变量为空。这个想法是将用户选择的产品保存在会话中,以便我可以在另一个页面中显示它。

在这里,我根据其 ID 显示所选产品。我开始会话并保存产品:

public function viewAction($id) {
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository('MpShopBundle:Product')->find($id);

    return $this->render('MpShopBundle:Frontend:product_details.html.twig', array(
        'product'=>$product
    ));

    $session = new Session();
    $session->start();

    $session->set('product', $product);
}

在这个控制器中,我得到了产品值:

public function summaryAction() {
    $session = $this->getRequest()->getSession();
    $product = $session->get('product');

    $em = $this->getDoctrine()->getManager();
    $products = $em->getRepository('MpShopBundle:Product')->findAll();

    return $this->render('MpShopBundle:Frontend:product_summary.html.twig', array('products' => $products));
}

现在在我的树枝上我这样做:{% set product = app.session.get('product') %} 并尝试获得像这样的产品属性{{ product.price }}。然后我得到上面的错误。

【问题讨论】:

  • 在将 $product 变量设置为会话变量之前检查它。
  • 你调试过产品的结构吗?
  • return 语句之后的所有代码都不会被执行。这是第一个错误。

标签: php symfony session


【解决方案1】:

尝试如下修改控制器,因为 Symfony 已经作为会话启动:

 public function viewAction($id)
        {

            $em = $this->getDoctrine()->getManager();
            $product = $em->getRepository('MpShopBundle:Product')->find($id);

            $session = $this->getRequest()->getSession();

            $session->set('product', $product);

            return $this->render('MpShopBundle:Frontend:product_details.html.twig', array(
            'product'=>$product
            ));


        } 

【讨论】:

  • 您的代码经过了一些调整。像其他 cmets 说代码必须在 return 语句之前才能工作。谢谢!
  • 我已经编辑了我的代码以在返回之前获取会话变量。不想迷惑别人!
【解决方案2】:
public function viewAction($id)
{
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository('MpShopBundle:Product')->find($id);

    $session = $this->getRequest()->getSession();
    $session->set('product', $product);
    return $this->render('MpShopBundle:Frontend:product_details.html.twig', array('product'=>$product));
} 

在此函数中更改您的代码,因为返回后它不会将您的值分配给会话变量。

【讨论】:

  • new Session 不正确。这是$this->get('session') 在容器外。
猜你喜欢
  • 1970-01-01
  • 2012-02-04
  • 2014-06-25
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 2017-11-17
相关资源
最近更新 更多