DEV Community

Paboda Hettiarachchi
Paboda Hettiarachchi

Posted on • Updated on

ViewModel to add a custom title in PDP - Magento 2

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


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();
Enter fullscreen mode Exit fullscreen mode


<referenceContainer name="">
    <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">
                <argument name="view_model" xsi:type="object">Vendor\Module\ViewModel\CustomTitle</argument>
Enter fullscreen mode Exit fullscreen mode


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

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

Top comments (1)

gayanhewa profile image
Gayan Hewa

Good stuff 👌