0

Good evening.

I need to add layout for products, which SKUs start from 9 (so 9XXXX).

I've read we can add this though handler or some other methods.

If someone had experience with that moment, please give answer.

Thanks :)

1

Try the following way:

app/code/SR/MagentoCommunity/etc/frontend/events.xml

<?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="layout_load_before">
        <observer name="add_custom_layout_handle" instance="SR\MagentoCommunity\Observer\LayoutLoadBefore"/>
    </event>
</config>

app/code/SR/MagentoCommunity/Observer/LayoutLoadBefore.php

<?php
namespace SR\MagentoCommunity\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Registry;

class LayoutLoadBefore implements ObserverInterface
{
    /**
     * @var Registry
     */
    protected $registry;

    /**
     * LayoutLoadBefore constructor.
     * @param Registry $registry
     */
    public function __construct(
        Registry $registry
    ) {
        $this->registry = $registry;
    }

    /**
     * @param Observer $observer
     * @return $this
     */
    public function execute(Observer $observer)
    {
        $action = $observer->getData('full_action_name');
        if ($action != 'catalog_product_view') {
            return $this;
        }

        /** @var \Magento\Catalog\Model\Product $product */
        $product = $this->registry->registry('product');
        if (!$product) {
            return $this;
        }

        /** @var \Magento\Framework\View\LayoutInterface $layout */
        $layout = $observer->getData('layout');
        if (strpos($product->getSku(), '9') === 0) {
            $layout->getUpdate()->addHandle('catalog_product_view_custom');
        }

        return $this;
    }
}

app/code/SR/MagentoCommunity/view/frontend/layout/catalog_product_view_custom.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Magento\Catalog\Block\Product\View" name="sample_test_template" as="sample_test_template" template="SR_MagentoCommunity::product/view/sample.phtml"/>
        </referenceContainer>
    </body>
</page>

app/code/SR/MagentoCommunity/view/frontend/templates/product/view/sample.phtml

<h1>This is Sample Template</h1>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.