Magento 2 How to override Magento\Customer\Block\Address\Book block in my custom module?
-
07-02-2021 - |
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.
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
Copy
Book.php
fromMagento\Customer\Block\Address\Book
toVendor/ModuleName/Block/Address/Book
Add your custom function inside book.php.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"/>
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);
}