How to extend the block file functionality?

Because the search popular terms page shows as empty, so I have extended the block file as the following. But it is not working.

/app/code/Talk/CustomSearch/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'CustomSearch',
    __DIR__
);

/app/code/Talk/CustomSearch/etc/module.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="CustomSearch" setup_version="1.0.0">
    </module>
</config>

/app/code/Talk/CustomSearch/etc/di.xml

<?xml version="1.0"?>
    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
      <preference for="Magento\Search\Block\Term" type="Talk\CustomSearch\Block\Term" />
    </config>

/app/code/Talk/CustomSearch/Block/Term.php

<?php

/**
 * Search term block
 */
namespace Talk\CustomSearch\Block;


class Term extends \Magento\Search\Block\Term
{


    /**
     * Load terms and try to sort it by names
     *
     * @return $this
     */
    protected function _loadTerms()
    {
        exit('LoadTerms');
    }
}

The function _loadTerms() is not called. How to extend the block in the magento-search module?

Module name in registration.php and module.xml is not defined correctly. Has to be Talk_CustomSearch. Please correct and try again.

  • yes, I have changed. – vinoth Jun 19 '17 at 6:30

Solution!

Change CustomSearch into Talk_CustomSearch for both registration.php and module.xml

Additionally, I have implemented the function in the file /app/code/Talk/CustomSearch/Block/Term.php

protected function _toHtml()
    {
        $this->setModuleName($this->extractModuleName('Magento\Search\Block\Term'));
        return parent::_toHtml();
    }

Full Code

<?php

/**
 * Search term block
 */
namespace Talk\CustomSearch\Block;


class Term extends \Magento\Search\Block\Term
{


    /**
     * Load terms and try to sort it by names
     *
     * @return $this
     */
    protected function _loadTerms()
    {
        exit('LoadTerms');
    }


    protected function _toHtml()
    {
        $this->setModuleName($this->extractModuleName('Magento\Search\Block\Term'));
        return parent::_toHtml();
    }
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.