How to add the simple product in a configurable product? And How to redirect parent product in a Configurable product.
Magento 2.0
I have created a module for Configurable. You need to follow the below steps:
Step 1: Create file module.xml under:
/app/code/STech/Configurable/etc/module.xml
with below content:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="STech_Configurable" setup_version="0.0.1"></module>
<sequence>
<module name="Magento_Backend"/>
<module name="Magento_Sales"/>
<module name="Magento_Quote"/>
<module name="Magento_Checkout"/>
</sequence>
</config>
Step 2: Create registration.php under:
/app/code/STech/Configurable/registration.php
with below content:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'STech_Configurable',
__DIR__
);
Step 3: Create registration.php under:
/app/code/STech/Configurable/etc/di.xml
with below content:
<?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="Magento\Catalog\Controller\Product\View">
<plugin name="stech_configurable_product_controller_view" type="STech\Configurable\Plugin\Catalog\Controller\Product\View" sortOrder="1"/>
</type>
</config>
Step 4: Create registration.php under:
/app/code/STech/Configurable/Plugin/Catalog/Controller/Product/View.php
with below content:
<?php
namespace STech\Configurable\Plugin\Catalog\Controller\Product;
class View
{
protected $http;
protected $productHelper;
protected $configurable;
public function __construct(
\Magento\Framework\App\Response\Http $http,
\Magento\Catalog\Helper\Product $productHelper,
\Magento\ConfigurableProduct\Model\Product\Type\Configurable $configurable
) {
$this->http = $http;
$this->productHelper =$productHelper;
$this->configurable = $configurable;
}
public function aroundExecute(
\Magento\Catalog\Controller\Product\View $subject,
\Closure $proceed
)
{
$productId = (int) $subject->getRequest()->getParam('id');
$parentIds = $this->configurable->getParentIdsByChild($productId);
$parentId = array_shift($parentIds);
if($parentId) {
$categoryId = (int)$subject->getRequest()->getParam('category', false);
$productId = (int)$parentId;
$params = new \Magento\Framework\DataObject();
$params->setCategoryId($categoryId);
/** @var \Magento\Catalog\Helper\Product $product */
$product = $this->productHelper->initProduct($productId, $subject, $params);;
$this->http->setRedirect($product->getProductUrl(), 301);
}
return $proceed();
}
}
Thats its. Flush the cache. Run setup upgrade and other required commands and check.
Hope this helps!