Symfony2 needs some clarity and guidance with a shopping cart (regarding quantity)

So, I have a shopping basket. I can add, remove and view products in the shopping cart. Now the problem is related to the increase and decrease in quantity. If, for example, a user wants to buy more than one product.

BACKGROUND:

There are two ways to increase the amount:

You can enlarge it every time you add a product from its details page. This part works and I do it like here:

if( isset($cart[$id]) ) {

            $qtyAvailable = $product->getStock();

                if ( $qtyAvailable > $cart[ $id ]) {
                    $cart[ $id ] = $cart[ $id ] + 1;
                } else {

                return $this->redirect($this->generateUrl('cart'));
            }


        } else {
            // if it doesnt make it 1
            $cart = $session->get('cart', array());
            $cart[$id] = 1;
        }

      

What is $ cart here?

As you can see, I am checking if the product id exists in the cart. If this happens, increase its value. My Cart array only has one key, which is the product id and I increment the value of the ids every time I add the same product.

Another way is to increase the quantity in the cart itself using the +, - buttons. I am stuck at this part.

I guess there are two ways to increase the amount here, using javascript or writing a similar function like from above (I prefer this one). Since I'm not used to javascript, the only way I can do this is by writing this:

<div class="input-append"><input class="span1" style="max-width:34px" placeholder="{{ key }}" id="appendedInputButtons" size="16" type="text">
<button class="btn" type="button" name="add" onclick='javascript: document.getElementById("appendedInputButtons").value++;'><i class="icon-minus"></i></button>
<button class="btn" type="button" name='subtract' onclick='javascript: document.getElementById("appendedInputButtons").value--;'><i class="icon-plus"></i></button>

      

However, this only changes the number on the screen, it does not increase or decrease the array itself. Maybe you can change the values ​​of the array using javascript?

UPDATE

Ok so I am trying to understand the code that one of the StackOverflow users provided, however I am having some problems.

So, in my branch, I did this:

<div class="input-append"><input class="span1" style="max-width:34px" name="quantity" placeholder="{{ key }}" id="appendedInputButtons" size="16" type="text" data-id="12">
                    <button class="btn" type="submit" value="increase"><a href="javascript:void(0)" class="plus"><i class="icon-minus"></i></button>
                    <button class="btn" type="button"><i class="icon-plus"></i></button>

      

Then in my controller I did like in the example:

/**
 * @Route("/cart/update", name="cart_update")
 */
public function cartUpdateAction( Request $request )
    {
        $response = new JsonResponse();
    $requestData = $request->request->all();
    $productid     = $requestData['product'];/** first put all validations not empty/ is numeric and exists in your db etc*/
    $quantity = $requestData['quantity'];/** first put all validations not empty/ is numeric etc */
    /** if all is good then put your logic*/
    $product = $em->getRepository('MpShopBundle:Product')->find($productid);
    $qtyAvailable = $product->getStock();
    $session = $this->getRequest()->getSession();
    $cart = $session->get('cart', array());

     if ( $qtyAvailable > $cart[ $productid ] ) {
        $cart[ $productid ] = $cart[ $productid ] + 1;
        $response->setData(array('success'=>true,'message'=>'Qunatity increased'));
    } else {
        $response->setData(array('success'=>false,'message'=>'Out of stock'));
    }
    return $response;
}

      

Now I am having trouble where do I need to write my javascript code? I read that you need to create a new .js file and add it using assetic, so I did it like this:

I added jquery library and my ajax script file to my base.twig.html files like this:

{% block javascripts %}

            {# Le Javascript #}         
                {% javascripts 


                    'bundles/mpFrontend/assets/js/jquery-1.11.2.min.js'         
                    'Mp/ShopBundle/Resources/js/scripts.js'   
                    %}      
                    <script src="{{ asset_url }}"></script>       
                {% endjavascripts %}

      

And then I extend base.html.twig on the branch I want to use ajax. However, nothing happens when I click the button. SO added ajax code incorrectly?

+3


source to share


1 answer


You can use jQuery and Ajax to fetch and send values ​​to the server, you must first include the library to use.

the sample markup will each element have its own container one text input or hidden, if you are using any js effect to increase the amount, make sure this input is updated every time the user action is incremented or decremented.

<div class="item">
    <input type="text" data-id="product id here" />
    <a href="javascript:void(0)" class="plus">+</a>
    <a href="javascript:void(0)">-</a>
</div>
<div class="item">...</div>
<div class="item">...</div>

      

initialize the click handler for binding with a plus class so you can send values ​​to the server to update the cart array



$('.plus').on('click', function (e) {
    $this = $(this);
    $.ajax({
        type: 'POST',
        url: 'server side action url here',// /cart/update 
        async: false,
        dataType: 'JSON',
        data: {product: $this.parent('.item').find('input').data('id'),quantity: $this.parent('.item').find('input').val()},
        success: function (data) {
          if(data.success == false){
           alert('error')
          }
        }
    });
});

      

On the server side, only execute the example code for the number of increments if you get an idea you can implement for the decrement script

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request; /** At the top of your controller*/
/**
 * @Route("/cart/update", name="cart_update")
 */
public function cartUpdateAction( Request $request ) {
    $response = new JsonResponse();
    $requestData = $request->request->all();
    $productid     = $requestData['product'];/** first put all validations not empty/ is numeric and exists in your db etc*/
    $quantity = $requestData['quantity'];/** first put all validations not empty/ is numeric etc */
    /** if all is good then put your logic*/
    $product = $em->getRepository('MpShopBundle:Product')->find($productid);
    $qtyAvailable = $product->getStock();
    $session = $this->getRequest()->getSession();
    $cart = $session->get('cart', array());
    if ( $qtyAvailable > $cart[ $productid ] ) {
        $cart[ $productid ] = $cart[ $productid ] + 1;
        $response->setData(array('success'=>true,'message'=>'Qunatity increased'));
    } else {
        $response->setData(array('success'=>false,'message'=>'Out of stock'));
    }
    return $response;
}

      

0


source







All Articles