Question

I want to override block Magento\Customer\Block\Address\Book in my custom module. And need to add a new function which returns module status enable/disable, which is defined in the model class. I need to call my custom function in book.phtml which is copied to my module.

Thanks.

Was it helpful?

Solution

Include the below line in your custom modules di.xml

<preference for="Magento\Customer\Block\Address\Book" type="<<Your Custom Modules Block File Path" />

And, in your custom modules block php file, override the desired method.

<?php

    namespace <<Custom Module Block Path>>;

    class CustomModuleBlockName extends \Magento\Customer\Block\Address\Book
    {
        public function <<methodname()
        {
            // Do your stuff here
        }
    }

OTHER TIPS

  1. Copy Book.php from Magento\Customer\Block\Address\Book to Vendor/ModuleName/Block/Address/Book Add your custom function inside book.php.

  2. In layout file, relate your template with the class file .

    <block class="Vendor/ModuleName/Block/Address/Book" name="customaddress" template="Vendor_ModuleName::your_layout_file.phtml"/>
    
  3. Within template file, call your custom function. $block->yourFunction()

I used layout xml to override phtml. i have blow code in my layout file for override.

We need to add all the dependencies in our module block file.

namespace Name\Module\Block\Rewrite\Address;

use Magento\Customer\Api\AddressRepositoryInterface; use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Model\Address\Mapper;

class Book extends \Magento\Customer\Block\Address\Book { protected $currentCustomer; protected $customerRepository; protected $addressRepository; protected $_addressConfig; protected $addressMapper; protected $_moduleStatusConfigProvider;

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    CustomerRepositoryInterface $customerRepository,
    AddressRepositoryInterface $addressRepository,
    \Magento\Customer\Helper\Session\CurrentCustomer $currentCustomer,
    \Magento\Customer\Model\Address\Config $addressConfig,
    Mapper $addressMapper,
    \Name\Module\Model\ModuleStatusConfigProvider $moduleStatusConfigProvider,
    array $data = []
) {
    $this->customerRepository = $customerRepository;
    $this->currentCustomer = $currentCustomer;
    $this->addressRepository = $addressRepository;
    $this->_addressConfig = $addressConfig;        
    $this->addressMapper = $addressMapper;
    $this->_moduleStatusConfigProvider = $moduleStatusConfigProvider;
    parent::__construct($context, $customerRepository,$addressRepository,$currentCustomer,$addressConfig,$addressMapper,$data);        
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top