How to customize Add to cart functionality based on product categories in Magento 2?Magento Product Add to Cart after Login for Selected CategoryRedirect “Add to Cart” from Category page to CMS pageBundled Product “Add to Cart” immediately?I want to add a product to cart programatically to cart when a product has custom optionAdd item(s) to cart programmatically with different lineMagento 1.8.x: Validate 'Add to Cart' Button on Category ViewNeed to add “Add to Cart” button Grouped product page in magento 2 for Main ProductM2: after add to cart showing error messageShow Pop Up when click on Add to cart checkbox for related products Magento 2.1.7?How and where to change add to cart message in Magento 2?

How to get cool night-vision without lame drawbacks?

What is the origin of Scooby-Doo's name?

Where can I find a database of galactic spectra?

Can the negators "jamais, rien, personne, plus, ni, aucun" be used in a single sentence?

Why is the voltage measurement of this circuit different when the switch is on?

I am completely new to Tales from the Floating Vagabond, how do I get started?

Find the probability that the 8th woman to appear is in 17th position.

Impossible darts scores

Can we put equal sign after aggregate functions in sql?

How would modern naval warfare have to have developed differently for battleships to still be relevant in the 21st century?

A STL-like vector implementation in C++

Fedora boot screen shows both Fedora logo and Lenovo logo. Why and How?

Why do some games show lights shine thorugh walls?

Employer wants to use my work email account after I quit

Unusual mail headers, evidence of an attempted attack. Have I been pwned?

Trainee keeps missing deadlines for independent learning

Require advice on power conservation for backpacking trip

Links to webpages in books

STM Microcontroller burns every time

In the Marvel universe, can a human have a baby with any non-human?

Why do textbooks often include the solutions to odd or even numbered problems but not both?

How is hair tissue mineral analysis performed?

Do I have any obligations to my PhD supervisor's requests after I have graduated?

Why aren't cotton tents more popular?



How to customize Add to cart functionality based on product categories in Magento 2?


Magento Product Add to Cart after Login for Selected CategoryRedirect “Add to Cart” from Category page to CMS pageBundled Product “Add to Cart” immediately?I want to add a product to cart programatically to cart when a product has custom optionAdd item(s) to cart programmatically with different lineMagento 1.8.x: Validate 'Add to Cart' Button on Category ViewNeed to add “Add to Cart” button Grouped product page in magento 2 for Main ProductM2: after add to cart showing error messageShow Pop Up when click on Add to cart checkbox for related products Magento 2.1.7?How and where to change add to cart message in Magento 2?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am using Magento 2.3.0



I have some products in my website which allows custom printing and these products are assigned in category "Printing Products". Now I want to customize add to cart functionality for these custom printing products. I don't want to add any other category products with these custom printing products. For Ex., Let's say When there is custom printing product is already added to a product and if I try to add any products other than "Printing product" category then this product must not be added to cart and an error message should be displayed.



In short, Custom Printing category products are not allowed to shop with other products. So, How can I do this?



EDIT : When the cart is empty or cart is having other product from "Printing Products" category then I should be able to add printing product into the cart and in this situation, if I try to add products other than "Printing Products" category then the error message should be shown.










share|improve this question






























    0















    I am using Magento 2.3.0



    I have some products in my website which allows custom printing and these products are assigned in category "Printing Products". Now I want to customize add to cart functionality for these custom printing products. I don't want to add any other category products with these custom printing products. For Ex., Let's say When there is custom printing product is already added to a product and if I try to add any products other than "Printing product" category then this product must not be added to cart and an error message should be displayed.



    In short, Custom Printing category products are not allowed to shop with other products. So, How can I do this?



    EDIT : When the cart is empty or cart is having other product from "Printing Products" category then I should be able to add printing product into the cart and in this situation, if I try to add products other than "Printing Products" category then the error message should be shown.










    share|improve this question


























      0












      0








      0








      I am using Magento 2.3.0



      I have some products in my website which allows custom printing and these products are assigned in category "Printing Products". Now I want to customize add to cart functionality for these custom printing products. I don't want to add any other category products with these custom printing products. For Ex., Let's say When there is custom printing product is already added to a product and if I try to add any products other than "Printing product" category then this product must not be added to cart and an error message should be displayed.



      In short, Custom Printing category products are not allowed to shop with other products. So, How can I do this?



      EDIT : When the cart is empty or cart is having other product from "Printing Products" category then I should be able to add printing product into the cart and in this situation, if I try to add products other than "Printing Products" category then the error message should be shown.










      share|improve this question
















      I am using Magento 2.3.0



      I have some products in my website which allows custom printing and these products are assigned in category "Printing Products". Now I want to customize add to cart functionality for these custom printing products. I don't want to add any other category products with these custom printing products. For Ex., Let's say When there is custom printing product is already added to a product and if I try to add any products other than "Printing product" category then this product must not be added to cart and an error message should be displayed.



      In short, Custom Printing category products are not allowed to shop with other products. So, How can I do this?



      EDIT : When the cart is empty or cart is having other product from "Printing Products" category then I should be able to add printing product into the cart and in this situation, if I try to add products other than "Printing Products" category then the error message should be shown.







      magento2 product cart addtocart






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 17 at 5:14









      Aasim Goriya

      3,2371 gold badge11 silver badges43 bronze badges




      3,2371 gold badge11 silver badges43 bronze badges










      asked Jun 14 at 11:23









      Chintan KaneriyaChintan Kaneriya

      4132 silver badges14 bronze badges




      4132 silver badges14 bronze badges




















          1 Answer
          1






          active

          oldest

          votes


















          1














          You can try the step below to restrict add to cart from diffrient categories.



          Assume you are using a custom module name "Company_MyModule".



          STEPP 1)



          Create di.xml under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/di.xml



          <?xml version="1.0"?>
          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
          <type name="MagentoCheckoutModelCart">
          <plugin name="restrictAddTocart"
          type="CompanyMyModuleModelPluginCart"/>
          </type>
          </config>


          Step 2)



          Create Cart.php under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin/Cart.php



          <?php

          namespace CompanyMyModuleModelPlugin;

          <?php

          namespace CompanyMyModuleModelPlugin;

          class Cart

          protected $productRepository;
          protected $storeManager;
          protected $checkoutSession;
          protected $logger;

          const PRINT_CATEGORY_ID = 4; // set print category ID

          public function __construct( MagentoCatalogApiProductRepositoryInterface $productrepositoryInterface, MagentoStoreModelStoreManagerInterface $storeManager, MagentoFrameworkSessionSessionManagerInterface $checkoutSession, PsrLogLoggerInterface $loggerInterface )

          $this->productRepository = $productrepositoryInterface;
          $this->storeManager = $storeManager;
          $this->checkoutSession = $checkoutSession;
          $this->logger = $loggerInterface;

          public function beforeAddProduct( MagentoCheckoutModelCart $subject, $productInfo, $requestInfo = null )

          $productId = $productInfo->getData('entity_id');
          $type_id = $productInfo->getData('type_id');
          $product = $this->productRepository->getById($productId);
          $categoryIds = $product->getCategoryIds();
          $this->logger->info("Current Product Category IDs",$categoryIds);

          if ( is_array($categoryIds) && !in_array(self::PRINT_CATEGORY_ID,$categoryIds) )
          throw new MagentoFrameworkExceptionLocalizedException(__('Since Print product exist in your cart, You only order from Print Category products'));
          return $this;


          return array(
          $productInfo,
          $requestInfo
          );







          share|improve this answer























          • I have created the module as you explained but when I ran upgrade command in SSH then it gave me an error "There are no commands defined in the "setup" namespace.". what can be the issue?

            – Chintan Kaneriya
            Jun 15 at 11:04











          • Now, this extension is working but I am not able to add printing products into cart even though the cart is empty. please check my edited question.

            – Chintan Kaneriya
            Jun 17 at 4:27













          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "479"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f278389%2fhow-to-customize-add-to-cart-functionality-based-on-product-categories-in-magent%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You can try the step below to restrict add to cart from diffrient categories.



          Assume you are using a custom module name "Company_MyModule".



          STEPP 1)



          Create di.xml under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/di.xml



          <?xml version="1.0"?>
          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
          <type name="MagentoCheckoutModelCart">
          <plugin name="restrictAddTocart"
          type="CompanyMyModuleModelPluginCart"/>
          </type>
          </config>


          Step 2)



          Create Cart.php under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin/Cart.php



          <?php

          namespace CompanyMyModuleModelPlugin;

          <?php

          namespace CompanyMyModuleModelPlugin;

          class Cart

          protected $productRepository;
          protected $storeManager;
          protected $checkoutSession;
          protected $logger;

          const PRINT_CATEGORY_ID = 4; // set print category ID

          public function __construct( MagentoCatalogApiProductRepositoryInterface $productrepositoryInterface, MagentoStoreModelStoreManagerInterface $storeManager, MagentoFrameworkSessionSessionManagerInterface $checkoutSession, PsrLogLoggerInterface $loggerInterface )

          $this->productRepository = $productrepositoryInterface;
          $this->storeManager = $storeManager;
          $this->checkoutSession = $checkoutSession;
          $this->logger = $loggerInterface;

          public function beforeAddProduct( MagentoCheckoutModelCart $subject, $productInfo, $requestInfo = null )

          $productId = $productInfo->getData('entity_id');
          $type_id = $productInfo->getData('type_id');
          $product = $this->productRepository->getById($productId);
          $categoryIds = $product->getCategoryIds();
          $this->logger->info("Current Product Category IDs",$categoryIds);

          if ( is_array($categoryIds) && !in_array(self::PRINT_CATEGORY_ID,$categoryIds) )
          throw new MagentoFrameworkExceptionLocalizedException(__('Since Print product exist in your cart, You only order from Print Category products'));
          return $this;


          return array(
          $productInfo,
          $requestInfo
          );







          share|improve this answer























          • I have created the module as you explained but when I ran upgrade command in SSH then it gave me an error "There are no commands defined in the "setup" namespace.". what can be the issue?

            – Chintan Kaneriya
            Jun 15 at 11:04











          • Now, this extension is working but I am not able to add printing products into cart even though the cart is empty. please check my edited question.

            – Chintan Kaneriya
            Jun 17 at 4:27















          1














          You can try the step below to restrict add to cart from diffrient categories.



          Assume you are using a custom module name "Company_MyModule".



          STEPP 1)



          Create di.xml under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/di.xml



          <?xml version="1.0"?>
          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
          <type name="MagentoCheckoutModelCart">
          <plugin name="restrictAddTocart"
          type="CompanyMyModuleModelPluginCart"/>
          </type>
          </config>


          Step 2)



          Create Cart.php under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin/Cart.php



          <?php

          namespace CompanyMyModuleModelPlugin;

          <?php

          namespace CompanyMyModuleModelPlugin;

          class Cart

          protected $productRepository;
          protected $storeManager;
          protected $checkoutSession;
          protected $logger;

          const PRINT_CATEGORY_ID = 4; // set print category ID

          public function __construct( MagentoCatalogApiProductRepositoryInterface $productrepositoryInterface, MagentoStoreModelStoreManagerInterface $storeManager, MagentoFrameworkSessionSessionManagerInterface $checkoutSession, PsrLogLoggerInterface $loggerInterface )

          $this->productRepository = $productrepositoryInterface;
          $this->storeManager = $storeManager;
          $this->checkoutSession = $checkoutSession;
          $this->logger = $loggerInterface;

          public function beforeAddProduct( MagentoCheckoutModelCart $subject, $productInfo, $requestInfo = null )

          $productId = $productInfo->getData('entity_id');
          $type_id = $productInfo->getData('type_id');
          $product = $this->productRepository->getById($productId);
          $categoryIds = $product->getCategoryIds();
          $this->logger->info("Current Product Category IDs",$categoryIds);

          if ( is_array($categoryIds) && !in_array(self::PRINT_CATEGORY_ID,$categoryIds) )
          throw new MagentoFrameworkExceptionLocalizedException(__('Since Print product exist in your cart, You only order from Print Category products'));
          return $this;


          return array(
          $productInfo,
          $requestInfo
          );







          share|improve this answer























          • I have created the module as you explained but when I ran upgrade command in SSH then it gave me an error "There are no commands defined in the "setup" namespace.". what can be the issue?

            – Chintan Kaneriya
            Jun 15 at 11:04











          • Now, this extension is working but I am not able to add printing products into cart even though the cart is empty. please check my edited question.

            – Chintan Kaneriya
            Jun 17 at 4:27













          1












          1








          1







          You can try the step below to restrict add to cart from diffrient categories.



          Assume you are using a custom module name "Company_MyModule".



          STEPP 1)



          Create di.xml under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/di.xml



          <?xml version="1.0"?>
          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
          <type name="MagentoCheckoutModelCart">
          <plugin name="restrictAddTocart"
          type="CompanyMyModuleModelPluginCart"/>
          </type>
          </config>


          Step 2)



          Create Cart.php under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin/Cart.php



          <?php

          namespace CompanyMyModuleModelPlugin;

          <?php

          namespace CompanyMyModuleModelPlugin;

          class Cart

          protected $productRepository;
          protected $storeManager;
          protected $checkoutSession;
          protected $logger;

          const PRINT_CATEGORY_ID = 4; // set print category ID

          public function __construct( MagentoCatalogApiProductRepositoryInterface $productrepositoryInterface, MagentoStoreModelStoreManagerInterface $storeManager, MagentoFrameworkSessionSessionManagerInterface $checkoutSession, PsrLogLoggerInterface $loggerInterface )

          $this->productRepository = $productrepositoryInterface;
          $this->storeManager = $storeManager;
          $this->checkoutSession = $checkoutSession;
          $this->logger = $loggerInterface;

          public function beforeAddProduct( MagentoCheckoutModelCart $subject, $productInfo, $requestInfo = null )

          $productId = $productInfo->getData('entity_id');
          $type_id = $productInfo->getData('type_id');
          $product = $this->productRepository->getById($productId);
          $categoryIds = $product->getCategoryIds();
          $this->logger->info("Current Product Category IDs",$categoryIds);

          if ( is_array($categoryIds) && !in_array(self::PRINT_CATEGORY_ID,$categoryIds) )
          throw new MagentoFrameworkExceptionLocalizedException(__('Since Print product exist in your cart, You only order from Print Category products'));
          return $this;


          return array(
          $productInfo,
          $requestInfo
          );







          share|improve this answer













          You can try the step below to restrict add to cart from diffrient categories.



          Assume you are using a custom module name "Company_MyModule".



          STEPP 1)



          Create di.xml under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/etc/di.xml



          <?xml version="1.0"?>
          <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
          <type name="MagentoCheckoutModelCart">
          <plugin name="restrictAddTocart"
          type="CompanyMyModuleModelPluginCart"/>
          </type>
          </config>


          Step 2)



          Create Cart.php under YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin



          File: YOUR-MAGENTO-ROOT/app/code/Company/MyModule/Model/Plugin/Cart.php



          <?php

          namespace CompanyMyModuleModelPlugin;

          <?php

          namespace CompanyMyModuleModelPlugin;

          class Cart

          protected $productRepository;
          protected $storeManager;
          protected $checkoutSession;
          protected $logger;

          const PRINT_CATEGORY_ID = 4; // set print category ID

          public function __construct( MagentoCatalogApiProductRepositoryInterface $productrepositoryInterface, MagentoStoreModelStoreManagerInterface $storeManager, MagentoFrameworkSessionSessionManagerInterface $checkoutSession, PsrLogLoggerInterface $loggerInterface )

          $this->productRepository = $productrepositoryInterface;
          $this->storeManager = $storeManager;
          $this->checkoutSession = $checkoutSession;
          $this->logger = $loggerInterface;

          public function beforeAddProduct( MagentoCheckoutModelCart $subject, $productInfo, $requestInfo = null )

          $productId = $productInfo->getData('entity_id');
          $type_id = $productInfo->getData('type_id');
          $product = $this->productRepository->getById($productId);
          $categoryIds = $product->getCategoryIds();
          $this->logger->info("Current Product Category IDs",$categoryIds);

          if ( is_array($categoryIds) && !in_array(self::PRINT_CATEGORY_ID,$categoryIds) )
          throw new MagentoFrameworkExceptionLocalizedException(__('Since Print product exist in your cart, You only order from Print Category products'));
          return $this;


          return array(
          $productInfo,
          $requestInfo
          );








          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jun 14 at 12:20









          Pritam Info 24Pritam Info 24

          1,2251 gold badge2 silver badges7 bronze badges




          1,2251 gold badge2 silver badges7 bronze badges












          • I have created the module as you explained but when I ran upgrade command in SSH then it gave me an error "There are no commands defined in the "setup" namespace.". what can be the issue?

            – Chintan Kaneriya
            Jun 15 at 11:04











          • Now, this extension is working but I am not able to add printing products into cart even though the cart is empty. please check my edited question.

            – Chintan Kaneriya
            Jun 17 at 4:27

















          • I have created the module as you explained but when I ran upgrade command in SSH then it gave me an error "There are no commands defined in the "setup" namespace.". what can be the issue?

            – Chintan Kaneriya
            Jun 15 at 11:04











          • Now, this extension is working but I am not able to add printing products into cart even though the cart is empty. please check my edited question.

            – Chintan Kaneriya
            Jun 17 at 4:27
















          I have created the module as you explained but when I ran upgrade command in SSH then it gave me an error "There are no commands defined in the "setup" namespace.". what can be the issue?

          – Chintan Kaneriya
          Jun 15 at 11:04





          I have created the module as you explained but when I ran upgrade command in SSH then it gave me an error "There are no commands defined in the "setup" namespace.". what can be the issue?

          – Chintan Kaneriya
          Jun 15 at 11:04













          Now, this extension is working but I am not able to add printing products into cart even though the cart is empty. please check my edited question.

          – Chintan Kaneriya
          Jun 17 at 4:27





          Now, this extension is working but I am not able to add printing products into cart even though the cart is empty. please check my edited question.

          – Chintan Kaneriya
          Jun 17 at 4:27

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Magento Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f278389%2fhow-to-customize-add-to-cart-functionality-based-on-product-categories-in-magent%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

          Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?