loading...

Magento 2, ViewModel to add a custom title in PDP

pabodah profile image Paboda Hettiarachchi ・1 min read

When there is a requirement to add an extra title in the product detail page in Magento 2, it is best to get it done via ViewModel
3 files to be edited,

  • PHP file for the ViewModel
  • layout file
  • phtml template file

app/code/Vendor/Module/ViewModel/CustomTitle.php

namespace Vendor\Module\ViewModel;

use Magento\Framework\Registry;

class CustomTitle implements \Magento\Framework\View\Element\Block\ArgumentInterface
{
    /**
     * @var Registry
     */
    protected $registry;

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

    /**
     * @return mixed
     */
    public function getOptionTitle()
    {
        return $this->registry->registry('current_product')->getHasOptions();
    }
}

app/design/frontend/Vendor/default/Magento_Catalog/layout/catalog_product_view.xml

<referenceContainer name="product.info.main">
    <container name="product.attribute.title.extra" as="productattributetitleextra" label="Product Attribute Title Extra" htmlTag="div" htmlClass="addon-title"  before="-">
        <block class="Magento\Framework\View\Element\Template" name="product.attribute.title.extra.template" template="Magento_Catalog::title.phtml">
            <arguments>
                <argument name="view_model" xsi:type="object">Vendor\Module\ViewModel\CustomTitle</argument>
            </arguments>
        </block>
    </container>        
</referenceContainer>

app/design/frontend/Vendor/default/Magento_Catalog/templates/title.phtml

<?php
/* @var $block \Magento\Framework\View\Element\Template */
?>
<?php $viewModel = $block->getData('view_model'); ?>

 <?php if ($viewModel->getOptionTitle()): ?>
    <h2>Customized title</h2>
 <?php endif; ?>

Posted on by:

pabodah profile

Paboda Hettiarachchi

@pabodah

I'm a Magento programer. Like to travel and have work life balance so love to work remotely.

Discussion

pic
Editor guide
 

Good stuff 👌