Jump to content

Maximum quantity of a product per category


yosku

Recommended Posts

Hello all,

I've been using Presta for some time now and I really like it. However I need your help for a case I have.

I am selling furniture via Prestashop and I would like to add a category where I can add some small "free" household stuff that clients can add to their cart as a gift. To do so I would like to limit the maximum quantity to 1 piece for a whole category (category name: Gifts). So if you choose one item from this category and add it to cart you can not add another item from the same category.

I would be interesting for me to have your suggestions :)

 

Thank you! 

 

EDIT: Prestashop version: 1.6.1.14

Edited by yosku (see edit history)
Link to comment
Share on other sites

  • 3 years later...

This is how I made it so that you can limit the total quantity of items allowed to be added to the cart out of specified Product IDs (eg: all the ones in a particular category).

In /classes/Cart.php

After this code:

         /* Check if the product is already in the cart */
        $cartProductQuantity = $this->getProductQuantity(
            $id_product,
            $id_product_attribute,
            (int) $id_customization,
            (int) $id_address_delivery
        );


Add in this code:
        

        // Products you want to limit the amount people can order across all these particular products
        $productsToLimit = array(4,5,6,10,12,14,16,18,20); // these are the Product IDs 
        $totalLimitOnProducts = 7; // this is the limit you want to set
        if(in_array($id_product,$productsToLimit)) {
          foreach($productsToLimit as $theproductId) {
            $getCountInCart = $this->getProductQuantity(
                $theproductId,
                $id_product_attribute,
                (int) $id_customization,
            );
            $countInCart += $getCountInCart['quantity']; //counts amount of each of those products already in the cart and sums it up
          }

          if($operator == 'up') { // make sure it's an increase to the quantity, not a decrease
            if($countInCart >= $totalLimitOnProducts) { /// if already reached limit on amount of products
              return false;
            } else if($quantity > ($totalLimitOnProducts-$countInCart)) { /// if quantity desired is more than amount allowed
              return false;
            }
          }
        }

I'm using Prestashop 1.7.7.7

  • Like 1
Link to comment
Share on other sites

  • 3 months later...
On 9/1/2021 at 12:27 PM, zon3d said:

This is how I made it so that you can limit the total quantity of items allowed to be added to the cart out of specified Product IDs (eg: all the ones in a particular category).

Hi

After couple changes in your published code I've managed to limit all products of the same type in cart to a fixed value.
Works tremendously, but that's one of needed changes to implement to make it fully working.

In next step I need to hide that + - buttons but that's an easy peasy thingy.

The problem I'm facing is a notice in modal window after adding the product that mentions: "Product successfully added to your cart".
Do you have any ideas how could I change content of this notice, or even better disable the cart button once a visitor adds the product to cart?
I checked the function that blocks the button after raising the product's quantity over its stock value, but that's not so easy to trigger as I thought.

 

edit: k, I've found a great tutor solving my problem in 100%
those interested in solution might find it on below page:
myprestamodules.com/blog/prestashop-17/mark-product-is-already-in-cart-in-prestashop-17.html

Edited by YoJoe (see edit history)
Link to comment
Share on other sites

  • 2 months later...
On 12/16/2021 at 2:12 AM, YoJoe said:

Hi

After couple changes in your published code I've managed to limit all products of the same type in cart to a fixed value.
Works tremendously, but that's one of needed changes to implement to make it fully working.

In next step I need to hide that + - buttons but that's an easy peasy thingy.

The problem I'm facing is a notice in modal window after adding the product that mentions: "Product successfully added to your cart".
Do you have any ideas how could I change content of this notice, or even better disable the cart button once a visitor adds the product to cart?
I checked the function that blocks the button after raising the product's quantity over its stock value, but that's not so easy to trigger as I thought.

 

edit: k, I've found a great tutor solving my problem in 100%
those interested in solution might find it on below page:
myprestamodules.com/blog/prestashop-17/mark-product-is-already-in-cart-in-prestashop-17.html

Hi,

I cannot get this to work at all. Products can still be added without problem, both from the homepage and the product page. Would you mind sharing your changes to the original code? I'm using PrestaShop 1.7.8.3

Link to comment
Share on other sites

4 hours ago, Prestafan1234 said:

Hi,

I cannot get this to work at all. Products can still be added without problem, both from the homepage and the product page. Would you mind sharing your changes to the original code? I'm using PrestaShop 1.7.8.3

The changes won't block adding to cart directly from category listing or homepage as the shop I was implementing those changes doesn't offer such functions. Thus I cannot tell you in which template file you should look for. But it shouldn't let the visitor adding more than 1 (or any other fixed value) same products to the cart, letting know the visitor that product is already in to cart.

Basically you need to make 3 changes,

1. as Zon3d described
/classes/cart.php 
Make an override of this file by copying it to /override/classes/  not to work on a core file

inside this file, as mentioned above, make changes after the lines:

/* Check if the product is already in the cart */
$cartProductQuantity = $this->getProductQuantity ...
by adding below code
 

//limit maximum product quantity a user can add to cart

        $totalLimitOnProducts = 1; // this is the max amount of same products you want to limit in cart
        $getCountInCart = $this->getProductQuantity(
                $id_product,
                $id_product_attribute,
                (int)$id_customization
                );
            $countInCart += $getCountInCart['quantity']; //counts amount of each of those products already in the cart and sums it up
            if ($operator == 'up') { // make sure it's an increase to the quantity, not a decrease
                if($countInCart >= $totalLimitOnProducts) { /// if already reached limit on amount of products
                  return false;
                } else if($quantity > ($totalLimitOnProducts-$countInCart)) { /// if quantity desired is more than amount allowed
                  return false;
                }



2. hide arrow buttons allowing to change product quantity on product page and inside cart
yourtheme//templates/checkout/_partials/cart-detailed-product-line.tpl

Find: <!--  product left body: description -->
And change this:

        <div class="row">
            {if isset($product.is_gift) && $product.is_gift}
          <div class="col-md-6 col-xs-6 qty">
              <span class="gift-quantity">{$product.quantity}</span>
          </div>
            {/if}
          <div class="col-md-6 col-xs-2 price">

into this

        <div class="row">
          <div class="col-md-6 col-xs-6 qty">
            {if isset($product.is_gift) && $product.is_gift}
              <span class="gift-quantity">{$product.quantity}</span>
            {else}
              <input
                class="js-cart-line-product-quantity"
                data-down-url="{$product.down_quantity_url}"
                data-up-url="{$product.up_quantity_url}"
                data-update-url="{$product.update_quantity_url}"
                data-product-id="{$product.id_product}"
                type="text"
                value="{$product.quantity}"
                name="product-quantity-spin"
                min="{$product.minimal_quantity}"
              />
            {/if}
          </div>
          <div class="col-md-6 col-xs-2 price">

since I don't remember the reason of making changes in this file I can't tell you now what for I made them. Make a backup before making changes and see if this one is truly needed.

3. file: yourtheme/templates/catalog/_partials/product-add-to-cart.tpl
check the tutorial linked by the end of my earlier post
you need to do this otherwise visitors will still be able to raise the amount of product in cart just by clicking multiple times on "add to cart" button

in this file  you also need to get rid of <> quantity change buttons.
Below is the code of all changes I made in this file taking also in the account changes from the tutorial. I just commented out code of the buttons so compare with your template file

 

<div class="product-add-to-cart">
  {if !$configuration.is_catalog}
    <span class="control-label">{l s='Quantity' d='Shop.Theme.Catalog'}</span>

	{if $product.availability == 'available' || $product.availability == 'last_remaining_items'}
	
    {block name='product_quantity'}
      <div class="product-quantity clearfix">
        
	{* hide product quantity input field 
		<div class="qty">
          <input
            type="text"
            name="qty"
            id="quantity_wanted"
            value="{$product.quantity_wanted}"
            class="input-group"
            min="{$product.minimal_quantity}"
            aria-label="{l s='Quantity' d='Shop.Theme.Actions'}"
          >
        </div>
    *}
		
		<div class="add">
		{$in_cart = 0}
		{foreach from=$cart['products'] item='cart_product' }
		  {*if $cart_product['id_product'] == $product.id*}
		  {if $cart_product['id_product'] == $product.id && $cart_product['id_product_attribute'] == $product.id_product_attribute}
			{$in_cart = 1}
		  {/if}
		{/foreach}
        <button
            class="btn btn-primary add-to-cart"
            data-button-action="add-to-cart"
            type="submit"
			{* disable button after adding product to cart or when product is already in cart *}
            {if !$product.add_to_cart_url || $in_cart}
              disabled style="filter: grayscale(0.5);box-shadow: inset 2px 2px 4px 0 rgba(0,0,0,.2);"
            {/if}
          >
            <i class="material-icons shopping-cart">&#xE547;</i>
			{* default addtocart button 
				{l s='Add to cart' d='Shop.Theme.Actions'} 
			*}
			{if $in_cart}
			  {l s='Already in cart' d='Shop.Theme.Actions'}
			{else}
			  {l s='Add to cart' d='Shop.Theme.Actions'}
			{/if}
		</button>
        </div>
      </div>
    {/block}
	{/if}
    {block name='product_availability'}
      <p id="product-availability">
        {if $product.show_availability && $product.availability_message}
          {if $product.availability == 'available'}
            <i class="material-icons rtl-no-flip product-available">&#xE5CA;</i>
			<span class="d-inline-block">{$product.availability_message}</span>
		  {elseif $product.availability == 'last_remaining_items'}
            <i class="material-icons product-last-items">&#xE002;</i>
			<span class="d-inline-block">{l s='Last Item In Stock' d='Shop.Theme.Actions'}{*$product.availability_message*}</span>
          {else}
            <i class="material-icons product-unavailable">&#xE14B;</i>
			<span class="d-inline-block">{l s='Sold out' d='Shop.Theme.Actions'}</span>
          {/if}        
		  {*$product.availability_message*}  
        {/if}
      </p>
    {/block}
    
    {block name='product_minimal_quantity'}
      <p class="product-minimal-quantity">
        {if $product.minimal_quantity > 1}
          {l
          s='The minimum purchase order quantity for the product is %quantity%.'
          d='Shop.Theme.Checkout'
          sprintf=['%quantity%' => $product.minimal_quantity]
          }
        {/if}
      </p>
    {/block}
  {/if}
</div>

 

this should do, at least in PS 1.7.4 in which I was implementing all needed changes

Link to comment
Share on other sites

Hi,

Thanks for the input. I could not get that to work either, as I could not add any products to cart at all after implementing the code.

I got the original code to work, but I had to remove this line:

(int) $id_customization,

It seems to work just as desired now, it is possible to add 1 product to the cart, even accross different products, which is what I need. I will just remove the arrows next to the quantity, as they do not work (it does not allow to add more than one product even if you move the count up)

Link to comment
Share on other sites

3 hours ago, Prestafan1234 said:

I got the original code to work, but I had to remove this line:

(int) $id_customization,

It seems to work just as desired now, it is possible to add 1 product to the cart, even accross different products, which is what I need. I will just remove the arrows next to the quantity, as they do not work (it does not allow to add more than one product even if you move the count up)

try using (int)$id_customization, there's no space after bracket in latest PS version.
After you got rid of this value check if changes work with product combinations as this value is afaik responsible for additional product attributes.
Unless you don't sell product with combinations.

Second thing is that you should check if updateQty function doesn't use $cartProductQuantity elsewhere, as changes use it's own $getCountInCart instead of $cartProductQuantity. Just switch it and check. I don't know the differences in latest PS version but you should notice what's going on. Try enabling debug mode.

Edited by YoJoe (see edit history)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...