Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8500111
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T00:51:16+00:00 2026-06-11T00:51:16+00:00

I’m learning my ways with Symfony2 while building a small e-commerce website for a

  • 0

I’m learning my ways with Symfony2 while building a small e-commerce website for a family-run wine importer. Slowly I’m gaining understanding of the Symfony2 concept but while moving on to building a cart bundle, I’m not quite sure what would be the correct (at least according to the Sf2 standards) way to implement this.

i made simple cart bundle based on session.

my problem is when i add product in cart then it work until product id is 0 to 9 and product quantity is increased automatically but after product id is 10 it’s quantity is equal to product id while it should be one.and also wrong product information is coming when we want to fetch product information.

I hope this is not a too wide question. I’m well aware of the fact that a truly robust shopping cart implementation is no small job.

My code is here:

  • CartController.php

    <?php
    
    namespace Webmuch\CartBundle\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
    use Symfony\Component\HttpFoundation\Response;
    
    use Webmuch\ProductBundle\Entity\Product;
    
    /**
     * @Route("/cart")
     */
    class CartController extends Controller
    {
    /**
     * @Route("/", name="cart")
     */
    public function indexAction()
    {
        // get the cart from  the session
        $session = $this->getRequest()->getSession();
        // $cart = $session->set('cart', '');
        $cart = $session->get('cart', array());
    
        // $cart = array_keys($cart);
        // print_r($cart); die;
    
        // fetch the information using query and ids in the cart
        if( $cart != '' ) {
    
            foreach( $cart as $id => $quantity ) {
                      $productIds[] = $id;
    
            }           
    
            if( isset( $productIds ) )
            {
                $em = $this->getDoctrine()->getEntityManager();
                $product = $em->getRepository('WebmuchProductBundle:Product')->findById( $productIds );
            } else {
                return $this->render('WebmuchCartBundle:Cart:index.html.twig', array(
                    'empty' => true,
                ));
            }
    
    
    
            return $this->render('WebmuchCartBundle:Cart:index.html.twig',     array(
                'product' => $product,
            ));
        } else {
            return $this->render('WebmuchCartBundle:Cart:index.html.twig',     array(
                'empty' => true,
            ));
        }
    }
    
    
    /**
     * @Route("/add/{id}", name="cart_add")
     */
    public function addAction($id)
    {
        // fetch the cart
        $em = $this->getDoctrine()->getEntityManager();
        $product = $em->getRepository('WebmuchProductBundle:Product')->find($id);
        //print_r($product->getId()); die;
        $session = $this->getRequest()->getSession();
        $cart = $session->get('cart', array());
    
    
        // check if the $id already exists in it.
        if ( $product == NULL ) {
             $this->get('session')->setFlash('notice', 'This product is not     available in Stores');          
            return $this->redirect($this->generateUrl('cart'));
        } else {
            if( isset($cart[$id]) ) {
    
                $qtyAvailable = $product->getQuantity();
    
                if( $qtyAvailable >= $cart[$id]['quantity'] + 1 ) {
                    $cart[$id]['quantity'] = $cart[$id]['quantity'] + 1; 
                } else {
                    $this->get('session')->setFlash('notice', 'Quantity     exceeds the available stock');          
                    return $this->redirect($this->generateUrl('cart'));
                }
            } else {
                // if it doesnt make it 1
                $cart = $session->get('cart', array());
                $cart[$id] = $id;
                $cart[$id]['quantity'] = 1;
            }
    
            $session->set('cart', $cart);
            return $this->redirect($this->generateUrl('cart'));
    
        }
    }
    
    
    /**
     * @Route("/remove/{id}", name="cart_remove")
     */
    public function removeAction($id)
    {
        // check the cart
        $session = $this->getRequest()->getSession();
        $cart = $session->get('cart', array());
    
        // if it doesn't exist redirect to cart index page. end
        if(!$cart) { $this->redirect( $this->generateUrl('cart') ); }
    
        // check if the $id already exists in it.
        if( isset($cart[$id]) ) {
            // if it does ++ the quantity
            $cart[$id]['quantity'] = '0';
            unset($cart[$id]);
            //echo $cart[$id]['quantity']; die();
        } else {
            $this->get('session')->setFlash('notice', 'Go to hell');    
            return $this->redirect( $this->generateUrl('cart') );
        }
    
        $session->set('cart', $cart);
    
        // redirect(index page)
        $this->get('session')->setFlash('notice', 'This product is Remove');
        return $this->redirect( $this->generateUrl('cart') );
    }
    }
    
  • index.html.twig:

    {% block body %}
    <h1>"FLAIRBAG" SHOPPING-CART</h1>
    
    <ul class="thumbnails">
    
    {% if empty %}
    <h5>Your shopping cart is empty.</h5>
    {% endif %}
    {% set cart = app.session.get('cart') %}
    
    
    {% if product %}
    
    
    <ul class="thumbnails">
    {% if app.session.hasFlash('notice') %} 
    
     <divclass="flash-notice">
    
      {{app.session.flash('notice') }} 
      {{ app.session.removeFlash('notice') }}
    
     </div>
    
    {% endif %}         
    {% for key, item in cart %}
        <p>ID:{{ key }}</p>
         <p>Quantity:{{ item }}</p>
         <button class="btn btn-primary"><a href="{{ path('cart_remove', {'id':     key}) }}">Remove</a></button>
    
       {% for item in product %}
            <p>{{ item.title }}</p>
        <p>{{ item.preview }}</p>
    {% endfor %}
    
    
    
    {% endfor %}
    </ul>
    
    {% endif %}
    </ul>
    
    <a href="{{ path('products') }}">Products</a>
    
    {% endblock %}
    

    Please help me with this.

    Thanks! I appreciate your help.

    • 1 1 Answer
    • 0 Views
    • 0 Followers
    • 0
    Share
    • Facebook
    • Report

    Leave an answer
    Cancel reply

    You must login to add an answer.

    Forgot Password?

    Need An Account, Sign Up Here

    1 Answer

    • Voted
    • Oldest
    • Recent
    • Random
    1. Editorial Team
      Editorial Team
      2026-06-11T00:51:18+00:00Added an answer on June 11, 2026 at 12:51 am

      The problem is in your cart array. According to your template, you expect to have an array with this structure:

      cart {
          id => quantity
      }
      

      i.e, the keys of the array are the ids of the product and the values are the quantities

      But then in your controller you do:

              $cart[$id] = $id;
              $cart[$id]['quantity'] = 1;
      

      Which is a very different thing. You should do:

              $cart[$id] = 1;
      

      And in all other places in your controller where you use $cart[$id][‘quantity’] use $cart[$id] instead. For example:

                 $cart[$id] = $cart[$id] + 1; 
      

      EDIT:

      In your controller do:

          $em = $this->getDoctrine()->getEntityManager();
          foreach( $cart as $id => $quantity ) {
                $product[] = $em->getRepository('WebmuchProductBundle:Product')->findById($id)
          }           
      
          if( !isset( $product ) )
          {
              return $this->render('WebmuchCartBundle:Cart:index.html.twig', array(
                  'empty' => true,
              ));
          }
      
      • 0
      • Reply
      • Share
        Share
        • Share on Facebook
        • Share on Twitter
        • Share on LinkedIn
        • Share on WhatsApp
        • Report

    Sidebar

    Related Questions

    I used javascript for loading a picture on my website depending on which small
    link Im having trouble converting the html entites into html characters, (&# 8217;) i
    I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
    I would like to run a str_replace or preg_replace which looks for certain words
    I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
    We're building an app, our first using Rails 3, and we're having to build
    I have an array which has BIG numbers and small numbers in it. I
    I've tracked down a weird MySQL problem to the two different ways I was
    I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
    That's pretty much it. I'm using Nokogiri to scrape a web page what has

    Explore

    • Home
    • Add group
    • Groups page
    • Communities
    • Questions
      • New Questions
      • Trending Questions
      • Must read Questions
      • Hot Questions
    • Polls
    • Tags
    • Badges
    • Users
    • Help
    • SEARCH

    Footer

    © 2021 The Archive Base. All Rights Reserved
    With Love by The Archive Base

    Insert/edit link

    Enter the destination URL

    Or link to existing content

      No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.