I'm trying to write a module to redirect simple products to their configurable products once each simple product is clicked on. I've done a bit research and wrote an Observer to catch event: controller_action_predispatch_catalog_product_view
Now I'm stuck in getting the clicked product (such as ID), from which I want to get its configurable product URL, then execute the redirect. Here is my Observer/redirect.php:
`
namespace Vendor_name\Module_name\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
class redirect implements ObserverInterface {
protected $_catalogProductTypeConfigurable;
protected $_productloader;
public function __construct(
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $_productloader,
\Magento\Catalog\Block\Product\Context $context,
\Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable $catalogProductTypeConfigurable,
\Magento\Catalog\Model\Session $catalogSession,
\Magento\Framework\App\ResponseFactory $responseFactory,
\Magento\Framework\UrlInterface $url
){
$this->_productloader = $_productloader;
$this->_catalogProductTypeConfigurable = $catalogProductTypeConfigurable;
$this->_catalogSession = $catalogSession;
$this->_responseFactory = $responseFactory;
$this->_url = $url;
}
public function execute(\Magento\Framework\Event\Observer $observer ) {
$_product = $observer->getEvent()->getProduct();//this dosen't seem to return anything at all
$product_id = $_product->getProductId();
$parentByChild = $this->_catalogProductTypeConfigurable->getParentIdsByChild($product_id);
//preset product options
if(isset($parentByChild[0])){
$id = $parentByChild[0];
$productCollection = $this->_productloader->create()->load($id);
$productAttributeOptions = $productCollection->getTypeInstance(true)->getConfigurableAttributesAsArray($productCollection);
$attributeOptions = array();
foreach ($productAttributeOptions as $productAttribute) {
$attributeOptions[$productAttribute['attribute_id']] = $_product->getData($productAttribute['attribute_code']);
}
}
$this->catalogSession->setSuperAttributes($attributeOptions);
//redirect to configurable product
$configProductUrl = $parentByChild->getProductUrl();
$this->_responseFactory->create()->setRedirect($configProductUrl)->sendResponse();
exit();
}
}
`