I’m trying to create admin configuration with two SKU’s fields, where later you can choose main product and second product will automatically add to cart for free.
So, I created system.xml file first:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<tab id="learning" translate="label" sortOrder="10">
<label>Learning</label>
</tab>
<section id="sku" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
<class>separator-top</class>
<label>Stock Keeping Unit</label>
<tab>learning</tab>
<resource>Learning_Sku::sku_config</resource>
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
<label>General Configuration</label>
<field id="sku_first" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>SKU №1</label>
<source_model>LearningSkuModelConfigProductlist</source_model>
<comment>First Stock Keeping Unit.</comment>
</field>
<field id="sku_second" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>SKU №2</label>
<source_model>LearningSkuModelConfigProductlist</source_model>
<comment>Second Stock Keeping Unit.</comment>
</field>
</group>
</section>
</system>
Then i created observer:
namespace LearningSkuObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoFrameworkAppRequestInterface;
class CustomObserver implements ObserverInterface
{
protected $product;
protected $cart;
protected $formKey;
public function __construct(
MagentoCatalogModelProductFactory $product,
MagentoFrameworkDataFormFormKey $formKey,
MagentoCheckoutModelCart $cart
){
$this->product = $product;
$this->formKey = $formKey;
$this->cart = $cart;
}
public function execute(MagentoFrameworkEventObserver $observer)
{
$items = $this->cart->getQuote()->getAllVisibleItems();
$isFreeItem = 0;
$isXItem = 0;
foreach($items as $item) {
// X is product id
if($item->getProductId()=="5"){
$isXItem = 1;
}
// Y is free product id
if($item->getProductId()=="2"){
$isFreeItem = 1;
}
}
if(!$isFreeItem && $isXItem) {
$params = array(
'form_key' => $this->formKey->getFormKey(),
'product_id' => 2, //product Id
'qty' =>1 //quantity of product
);
$product = $this->_product->create()->load(2);
$this->cart->addProduct($product, $params);
$this->cart->save();
}
}
}
And also events.xml for it:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_submit_all_after">
<observer name="CustomObserver" instance="LearningSkuObserverCustomObserver"/>
</event>
</config>
But it’s doesn’t working together. I don’t know if I do that task correctly. If yes, how combine all this code? Thanks a lot for helping!