cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 2 update layout using attribute sets

Magento 2 update layout using attribute sets

I have to create new layout on product view page using xml on the bases of product attribute set......

Trying this but no luck: layout/catalog_product_view_attribute_set_id_10.xml


Any idea to achieve this?

1 REPLY 1

Re: Magento 2 update layout using attribute sets

This helper

 

Magento\Catalog\Helper\Product\View

Is responsible for updating layout handlers before rendering a product page.

In the method initProductLayout you can call the code: 

$resultPage->addPageLayoutHandles(
['id' => $product->getId(), 'sku' => $urlSafeSku, 'type' => $product->getTypeId()]
);

This code should (theoretically) add the following handlers:

catalog_product_view_id_{product_id}
catalog_product_view_sku_{product_sku}
catalog_product_view_type_{type_id}

The code below will let you add these handlers:

/**
 * Add layout updates handles associated with the action page
 *
 * @param array|null $parameters page parameters
 * @param string|null $defaultHandle
 * @return bool
*/
public function addPageLayoutHandles(array $parameters = [], $defaultHandle = null) {
$handle = $defaultHandle ? $defaultHandle : $this->getDefaultLayoutHandle();
$pageHandles = [$handle];
foreach ($parameters as $key => $value) {
$pageHandles[] = $handle . '_' . $key . '_' . $value;
}
// Do not sort array going into add page handles. Ensure default layout handle is added first.
return $this->addHandle($pageHandles);
}


Here's what you'll get for a simple product when running this method in debug

a9af62b3079d74c29fe0a21bdf7720ce.png

 

As you can see, the catalog_product_view_type_simple has been added.

This is how the whole list will look like:

883a3632df7e24446d1448b2cbdfc331.png

 

If you need to add a rule to render a handler for a product ID attribute, you'll need a plugin for this method, that will add:

 

$resultPage->addPageLayoutHandles(
['attribute_set_id' => $product->getAttributeSetId()]
);


Thus, every product will get equipped with a handler.

catalog_product_view_attribute_set_id_{attribute_set_id}.

P.S. If you don't know hot to create a plugin, just let us know and we'll describe you the requested set of actions.


______________________________________________________________
Innovative, top-performing Magento Extensions (with an array of FREE tools).