Magento – magento 2 change page title on registration page

blocksmagento2pagepage-title

On the customer registration page, I need to change the page title depending on the condition.
In my custom module I try extend \Magento\Customer\Block\Form\Register
method protected function _prepareLayout(). My code is:

namespace Dv\RegistrationNotify\Block\Customer\Block\Form;
class Register extends \Magento\Customer\Block\Form\Register
{
    protected function _prepareLayout()
    {
        if(my condition){
            $this->pageConfig->getTitle()->set(__('Custom title Create New Customer Account'));
        } else {
            $this->pageConfig->getTitle()->set(__('Create New Customer Account'));
        }
        return parent::_prepareLayout();
    }
}

in di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Customer\Block\Form\Register" type="Dv\RegistrationNotify\Block\Customer\Block\Form\Register" />
</config>

But in result title doesn't change and page is empty
enter image description here

How can I change the title depending on the condition ?

Best Answer

The fact that you're calling the following code after your modification will overwrite your change:

return parent::_prepareLayout();

As it will basically do the following:

    if(my condition){
        $this->pageConfig->getTitle()->set(__('Custom title Create New Customer Account'));
    } else {
        $this->pageConfig->getTitle()->set(__('Create New Customer Account'));
    }
    $this->pageConfig->getTitle()->set(__('Create New Customer Account'));
    return $this;

To fix that replace your code with:

parent::_prepareLayout();
if(my condition){
    $this->pageConfig->getTitle()->set(__('Custom title Create New Customer Account'));
} else {
    $this->pageConfig->getTitle()->set(__('Create New Customer Account'));
}
return $this;