3

I want to show a minicart only for a specific customer group but I am unable to find the exact solution. If anyone knows please let me know. Thanks

5
1

You need to create custom module for it as below.

Vendor/ExtendedMinicart/registration.php

<?php
/**
 * Copyright © DevAwesome All rights reserved.
 * See COPYING.txt for license details.
 */
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Vendor_ExtendedMinicart', __DIR__);

Vendor/ExtendedMinicart/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="Vendor_ExtendedMinicart">
        <sequence>
            <module name="Magento_Checkout"/>
        </sequence>
    </module>
</config>

Create system configuration to set customer group to which minicart is displayed

Vendor/ExtendedMinicart/etc/adminhtml/system.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="checkout" sortOrder="10" showInWebsite="1" showInStore="1" showInDefault="1" translate="label">
            <label>Checkout</label>
            <tab>sales</tab>
            <resource>Vendor_ExtendedMinicart::config_vendor_extendedminicart</resource>
            <group id="sidebar" sortOrder="10" showInWebsite="1" showInStore="1" showInDefault="1" translate="label">
                <label>Sidebar</label>
                <field id="minicart_display_customer_group" type="multiselect" sortOrder="10" showInWebsite="1" showInStore="1" showInDefault="1" translate="label">
                    <label>Display to Customer Group</label>
                    <comment>Minicart is only visible to selected customer groups</comment>
                    <source_model>Magento\Customer\Model\Customer\Source\Group</source_model>
                </field>
            </group>
        </section>
    </system>
</config>

Create helper to get system configuration value

Vendor/ExtendedMinicart/Helper/Data.php

<?php
/**
 * Copyright © Demo All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Vendor\ExtendedMinicart\Helper;

use Magento\Framework\App\Helper\AbstractHelper;

class Data extends AbstractHelper
{

    /**
    * Minicart customer group display config path
    */
    const XML_PATH_MINICART_DISPLAY_CONFIG = 'checkout/sidebar/minicart_display_customer_group';

    /**
     * @param \Magento\Framework\App\Helper\Context $context
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context
    ) {
        parent::__construct($context);
    }

    public function getMinicartDisplayConfig()
    {
        return $this->scopeConfig->getValue(
            self::XML_PATH_MINICART_DISPLAY_CONFIG,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

Create preference to default block for minicart and add custom function to check minicart should be displayed or not

Vendor/ExtendedMinicart/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\Checkout\Block\Cart\Sidebar" type="Vendor\ExtendedMinicart\Rewrite\Magento\Checkout\Block\Cart\Sidebar"/>
</config>

Vendor/ExtendedMinicart/Rewrite/Magento/Checkout/Block/Cart/Sidebar.php

<?php
/**
 * Copyright © Demo All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace Vendor\ExtendedMinicart\Rewrite\Magento\Checkout\Block\Cart;

use Magento\Customer\Model\Context as CustomerContext;

class Sidebar extends \Magento\Checkout\Block\Cart\Sidebar
{
    /**
     * Customer session
     *
     * @var \Magento\Framework\App\Http\Context
     */
    protected $httpContext;

    /**
     * @var \Vendor\ExtendedMinicart\Helper\Data
     */
    protected $customHelper;

    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $customCustomerSession;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Catalog\Helper\Image $imageHelper
     * @param \Magento\Customer\CustomerData\JsLayoutDataProviderPoolInterface $jsLayoutDataProvider
     * @param array $data
     * @param \Magento\Framework\Serialize\Serializer\Json|null $serializer
     * @throws \RuntimeException
     */
    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 = [],
        \Magento\Framework\Serialize\Serializer\Json $serializer = null,
        \Magento\Framework\App\Http\Context $httpContext,
        \Vendor\ExtendedMinicart\Helper\Data $customHelper
    ) {
        $this->httpContext = $httpContext;
        $this->customHelper = $customHelper;
        $this->customCustomerSession = $customerSession;
        parent::__construct(
            $context,
            $customerSession,
            $checkoutSession,
            $imageHelper,
            $jsLayoutDataProvider,
            $data,
            $serializer
        );
    }

    public function isMinicartCustomerGroupDisplay()
    {
        $enabledCustomerGroups = $this->customHelper->getMinicartDisplayConfig();
        $enabledCustomerGroups = explode(',', $enabledCustomerGroups);
        
        if(in_array(32000, $enabledCustomerGroups)){
            return true;
        }
        
        if($this->httpContext->getValue(CustomerContext::CONTEXT_AUTH)){
            $customerGroupId = $this->customCustomerSession->getCustomer()->getGroupId();
        }else{
            $customerGroupId = 0;
        }
        
        if(in_array($customerGroupId, $enabledCustomerGroups)){
            return true;
        }
        return false;
    }
}

Override default minicart.phtml in your custom module.

Vendor/ExtendedMinicart/view/frontend/layout/default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="minicart">
            <action method="setTemplate">
                <argument name="template" xsi:type="string">Vendor_ExtendedMinicart::cart/minicart.phtml</argument>
            </action>
        </referenceBlock>
    </body>
</page>

Vendor/ExtendedMinicart/view/frontend/templates/cart/minicart.phtml

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/** @var $block \Magento\Checkout\Block\Cart\Sidebar */
/** @var \Magento\Framework\View\Helper\SecureHtmlRenderer $secureRenderer */
?>
<?php $isVisible = $block->isMinicartCustomerGroupDisplay(); ?>
<?php if($isVisible): ?>
    <div data-block="minicart" class="minicart-wrapper">
        <a class="action showcart" href="<?= $block->escapeUrl($block->getShoppingCartUrl()) ?>"
           data-bind="scope: 'minicart_content'">
            <span class="text"><?= $block->escapeHtml(__('My Cart')) ?></span>
            <span class="counter qty empty"
                  data-bind="css: { empty: !!getCartParam('summary_count') == false && !isLoading() },
                   blockLoader: isLoading">
                <span class="counter-number"><!-- ko text: getCartParam('summary_count') --><!-- /ko --></span>
                <span class="counter-label">
                <!-- ko if: getCartParam('summary_count') -->
                    <!-- ko text: getCartParam('summary_count') --><!-- /ko -->
                    <!-- ko i18n: 'items' --><!-- /ko -->
                <!-- /ko -->
                </span>
            </span>
        </a>
        <?php if ($block->getIsNeedToDisplaySideBar()):?>
            <div class="block block-minicart"
                 data-role="dropdownDialog"
                 data-mage-init='{"dropdownDialog":{
                    "appendTo":"[data-block=minicart]",
                    "triggerTarget":".showcart",
                    "timeout": "2000",
                    "closeOnMouseLeave": false,
                    "closeOnEscape": true,
                    "triggerClass":"active",
                    "parentClass":"active",
                    "buttons":[]}}'>
                <div id="minicart-content-wrapper" data-bind="scope: 'minicart_content'">
                    <!-- ko template: getTemplate() --><!-- /ko -->
                </div>
                <?= $block->getChildHtml('minicart.addons') ?>
            </div>
        <?php else: ?>
            <?php $scriptString = <<<script
                require(['jquery'], function ($) {
                    $('a.action.showcart').click(function() {
                        $(document.body).trigger('processStart');
                    });
                });
    script;
            ?>
            <?= /* @noEscape */ $secureRenderer->renderTag('script', [], $scriptString, false); ?>
        <?php endif ?>
        <?= /* @noEscape */ $secureRenderer->renderTag('script', [], 'window.checkout = ' .
         /* @noEscape */ $block->getSerializedConfig(), false); ?>
        <script type="text/x-magento-init">
        {
            "[data-block='minicart']": {
                "Magento_Ui/js/core/app": <?= /* @noEscape */ $block->getJsLayout() ?>
            },
            "*": {
                "Magento_Ui/js/block-loader": "<?= $block->escapeJs(
                    $block->escapeUrl($block->getViewFileUrl('images/loader-1.gif'))
                ) ?>"
            }
        }
        </script>
    </div>
<?php endif; ?>

You can download the complete module from here and try it on blank magento setup.

I hope it works for you. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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