1

I wanted to make changes in _prepareLayout() in block. Code is as follow:

Block: Magento\Catalog\Block\Category\View

protected function _prepareLayout()
{
    parent::_prepareLayout();

    $this->getLayout()->createBlock(\Magento\Catalog\Block\Breadcrumbs::class);

    $category = $this->getCurrentCategory();
    if ($category) {
        $title = $category->getMetaTitle();
        if ($title) {
            $this->pageConfig->getTitle()->set($title);
        }
        $description = $category->getMetaDescription();
        if ($description) {
            $this->pageConfig->setDescription($description);
        }
        $keywords = $category->getMetaKeywords();
        if ($keywords) {
            $this->pageConfig->setKeywords($keywords);
        }
        if ($this->_categoryHelper->canUseCanonicalTag()) {
            $this->pageConfig->addRemotePageAsset(
                $category->getUrl(),
                'canonical',
                ['attributes' => ['rel' => 'canonical']]
            );
        }

        $pageMainTitle = $this->getLayout()->getBlock('page.main.title');
        if ($pageMainTitle) {
            $pageMainTitle->setPageTitle($this->getCurrentCategory()->getName());
        }
    }

    return $this;
}

As per above code, I want to make change in below data:

if ($this->_categoryHelper->canUseCanonicalTag()) {
      $this->pageConfig->addRemotePageAsset(
          $category->getUrl(),
          'canonical',
          ['attributes' => ['rel' => 'canonical']]
      );
}

Help me to change the parameter passed to addRemotePageAsset() by overriding block.

0

you can not override protected methods in Magento 2, only the public method can be overridden using plugin or preference. there is no way to override protected and private method in Magento 2.

  • So how can i add custom code to _prepareLayout() as i have mentioned in my code? – Parthavi Mar 14 at 5:17
  • using preference we can rewrite the whole class, I don't know about what you've mentioned. Give me any document where it shows it cannot possible to override a protected function – Prathap Gunasekaran Mar 14 at 5:18
  • @Parthavi have a look at it magento.stackexchange.com/questions/126260/… – Prathap Gunasekaran Mar 14 at 5:20
  • @PrathapGunasekaran u mean that we can use preference for overwriting protected method – Parthavi Mar 14 at 5:24
  • Yes we can use it. – Prathap Gunasekaran Mar 14 at 5:24

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.