Posted on

How to override cartaddcontroller in magento 2?

I want this function in code StwBuyXGetY BuyXGetY ControllerCheckoutCartAdd.php(this is written in magento 1.9, I want to convert it into magento 2). But I cant add any new function in add controller. Any help will be appreciated.

public function buyXgetYfree()
{

$cart = $this->_getCart();
/* check if cart is empty */
if (!$this->_getCart()->getQuote()->getItemsCount()) {

return;
}

$buyProductXID = explode (“,”,Mage::getStoreConfig(‘buyxgety_section1/general/productx_product_id’));
$buyProductYID = explode (“,”,Mage::getStoreConfig(‘buyxgety_section1/general/producty_product_id’));
$buyProductXminQty = explode (“,”,Mage::getStoreConfig(‘buyxgety_section1/general/productx_required_qty’));
$buyProductXmaxQty = explode (“,”,Mage::getStoreConfig(‘buyxgety_section1/general/productx_limit_qty’));
$buyProductYDescription = explode (“,”,Mage::getStoreConfig(‘buyxgety_section1/general/producty_description’));

$error=”A BuyXGetY Extension cart error was detected!”;

try
{
for($i = 0; $i < count($buyProductXID); $i++){
if (empty($buyProductYDescription[$i])) {
$buyProductYDescription[$i]=”free gift”;
}
if (empty($buyProductXID[$i])) {
$buyProductXID[$i]=”0″;
}
if (empty($buyProductYID[$i])) {
$buyProductYID[$i]=”0″;
}
if (empty($buyProductXminQty[$i])) {
$buyProductXminQty[$i]=”999″;
}
if (empty($buyProductXmaxQty[$i])) {
$buyProductXmaxQty[$i]=”0″;
}
if ($buyProductXID[$i] !=”0″ && $buyProductYID[$i] !=”0″) {
if ($this->isProductYUnique())
{

$this->buyXgetYfreeCartUpdate((int)$buyProductXID[$i],(int)$buyProductXminQty[$i],(int)$buyProductYID[$i],$buyProductYDescription[$i],(int)$buyProductXmaxQty[$i]);
} else {
$error = “Error in Buy X configuration – Product Y is not unique across all extension settings.”;
throw new Exception($error);
break;
}
}

}

} catch (Exception $ex) {

$cart->getCheckoutSession()->addError($this->__($error));
$this->sendErrorEmail($error);
}
}

di.xml

<?xml version=”1.0″?>
<config xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=”../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd”>
<type name=”MagentoCheckoutControllerCartAdd”>
<plugin name=”buy-x-get-y” type=”StwBuyXGetYBuyXGetYPluginControllerCheckoutCartAdd” sortOrder=”1″ />
</type>
</config>

code StwBuyXGetY BuyXGetY ControllerCheckoutCartAdd.php

namespace StwBuyXGetYBuyXGetYPluginControllerCheckoutCart;
class Add
{
public function aroundExecute(MagentoCheckoutControllerCartAdd $add, callable $proceed, OutputInterface $output)
{
$this->buyXgetYfree();
$returnValue = $proceed();
return $returnValue;
}
public function buyXgetYfree()
{
echo “buyXgetYfree”; // this is dummy content
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *