简体   繁体   中英

Symfony2 Impossible to access an attribute on a NULL variable with sessions

I am getting the error as my title says but I cant figure out why is my variable null. The idea is to save the users selected product in a session so that i can show it in another page.

Here i am showing the selected product based on its id. I start the session and I save the product:

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);
}

In this controller I get the products values:

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));
}

Now in my twig I do this: {% set product = app.session.get('product') %} and the try to get the products attributes like this {{ product.price }} . And then i get the error above.

Try modifying the controller as below because Symfony has already started as session:

 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
            ));


        } 
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));
} 

change your code in this function because after return it will not assign your value to session variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM