Magento 2 – Adding Custom Layout Handle for Layouts via Product Admin Page

event-observerlayoutmagento2plugin

I want separate layout handles defined for products dependent on their layout set via the layout options for product within admin (1 column, 2 column left, 2 column right).

I need to set additional instructions to move and remove blocks based on the layout set. For example set a product to 1 column and update the catalog_product_view_layout_1column.xml file to remove blocks.

I have tried with both an observer and plugin to try and set this additional handle however am having difficulty. Below is how I tried to achieve with plugin method:

<type name="Magento\Catalog\Helper\Product\View">
    <plugin name="Vendor_Module_LayoutMods" type="Vendor\Module\Plugin\LayoutMod" />
</type>  

di.xml

<?php

namespace Vendor\Module\Plugin;

class LayoutMod
{
    public function aroundinitProductLayout(
        \Magento\Catalog\Helper\Product\View $subject,
        callable $proceed,
        \Magento\Framework\View\Result\Page $resultPage,
        $product,
        $params = null
    ) {
        $result = $proceed($resultPage, $product, $params);
        $resultPage->addPageLayoutHandles(['layout' => $product->getData('page_layout')], 'catalog_product_view');
        return $result;
    }
}

plugin/LayoutMod.php

This seems to add the handle in that $resultPage->getLayout()->getUpdate()->getHandles() shows my new custom handle catalog_product_view_layout_1column catalog_product_view_layout_1column.xml does not seem to be processed. catalog_product_view_id_123.xml does work however fine and blocks are removed. My xml is currently pretty simple as I test:

<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <attribute name="class" value="my-css-class"/>
        <referenceBlock name="product.info.main" remove="true"/>
    </body>
</page>

Magento_Catalog/layout/catalog_product_view_layout_1column.xml

I'm wondering can help explain why my new handle is not working?

Best Answer

The below seemed to work for me, the key was modifying what was returned:

   class LayoutMod
   {
      public function beforeInitProductLayout(
          \Magento\Catalog\Helper\Product\View $subject,
          \Magento\Framework\View\Result\Page $resultPage, 
          \Magento\Catalog\Model\Product $product, 
          $params = null
      ) {
          $resultPage->addPageLayoutHandles(['layout' => $product->getData('page_layout')], 'catalog_product_view');
          return [$resultPage, $product, $params];
      }
   }
Related Topic