Question

In the layout file app/code/Magento/Checkout/view/frontend/layout/default.xml

<block class="Magento\Checkout\Block\Cart\Sidebar" name="minicart" as="minicart" after="logo" template="cart/minicart.phtml">

I would like to add a new method to block Sidebar.php.

Then call in the template and the minicart.phtml.

I found in app/code/Magento/Customer/etc/frontend/di.xml:

<type name="Magento\Checkout\Block\Cart\Sidebar">
    <plugin name="customer_cart" type="\Magento\Customer\Model\Cart\ConfigPlugin" />
</type>

so I cant't use preference for Magento\Checkout\Block\Cart\Sidebar to add function in Sidebar.php.

Preference didn't work: app/code/Vendor/Modulename/etc/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Checkout\Block\Cart\Sidebar" type="Vendor\Modulename\Block\Cart\Sidebar" />
</config>

block file Vendor\Modulename\Block\Cart\Sidebar

class Sidebar extends \Magento\Checkout\Block\Cart\Sidebar
{
    protected $_logger;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Catalog\Helper\Image $imageHelper,
        \Magento\Customer\CustomerData\JsLayoutDataProviderPoolInterface $jsLayoutDataProvider,
        array $data
    ){
        $this->_logger = $context->getLogger();
        parent::__construct($context, $customerSession, $checkoutSession, $imageHelper, $jsLayoutDataProvider, $data);
    }

    public function getCheckoutUrl()
    {
        $this->_logger->addDebug("AAAAAAAAAAA");
        return parent::getCheckoutUrl(); // TODO: Change the autogenerated stub
    }

}

In var/log/debug.log, there is nothing to print

Was it helpful?

Solution 2

Magento2.1 fix plugin and preference problem

OTHER TIPS

You have to first override block for add new function in sidebar.php file.

You cant use plugin method for add new function in block file. You can use plugin method to overrider already defined public function in file.

You must have to overrider sidebar.php file and add new function inside sidebar.php file after adding function you can call those function inside your template file.

under

Vendor/Modulename/etc/di.xml

file,

<?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\Checkout\Block\Cart\Sidebar" type="Vendor/Modulename/Block/Cart/Sidebar" />

</config>

Inside sidebar.php file,

Vendor/Modulename/Block/Cart/Sidebar.php

you can define your new function.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top