1

I would like to pass a PHP session variable flag to mini cart-mixin.js dynamically. I followed the below steps mentioned here using the Config Provider concept I am able to pass variable to only cart page hence for remaining pages the condition is not satisfied facing an issue can any once advise?

Note: I would like to hide proceed to checkout button on cart page.

app/code/Test/Demo/view/frontend/requirejs-config.js

var config = {
    map: {
    '*': {
    'Magento_Checkout/template/minicart/content.html':
    'Test_Demo/template/minicart/content.html'
    }
},
config: {
    mixins: {
    'Magento_Checkout/js/view/minicart': {
    'Test_Demo/js/view/minicart-mixin': true
    }
  }
}

};

app/code/Test/Demo/view/frontend/web/js/view/minicart-mixin.js

define([
    'uiComponent',
    'Magento_Customer/js/customer-data',
    'jquery',
    'ko',
    'underscore',
    'sidebar',
    'mage/translate',
    'mage/dropdown'
], function (Component, customerData, $, ko, _) {
    'use strict';

    var mixin = {
        isButtonEnable: function () {
            console.log("isButtonEnable calling");

            /*You can add your condition here based on your requirements.*/
            //console.log(window.checkoutConfig.session_VIEUserData);
            if(window.checkoutConfig.session_VIEUserData){
                return true; //hide button
            }else {
                return false;  //show button
            }
        }
    };

    return function (target) {
        return target.extend(mixin);
    };
});

app/code/Test/Demo/etc/frontend/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">
   <type name="Magento\Checkout\Model\CompositeConfigProvider">
       <arguments>
           <argument name="configProviders" xsi:type="array">
               <item name="additional_provider" xsi:type="object">Test\Demo\Model\AdditionalConfigProvider</item>
           </argument>
       </arguments>
   </type>
</config>

app/code/Test/Demo/Model/AdditionalConfigProvider.php

<?php
namespace Test\Demo\Model;
use Magento\Framework\Session\SessionManager;

class AdditionalConfigProvider implements \Magento\Checkout\Model\ConfigProviderInterface
{
    /**
     * @var SessionManager
    */
    private $coreSession;

    /**
     * @param SessionManager $sessionManager
     */
    public function __construct(
        SessionManager $sessionManager
    ) {
        $this->coreSession = $sessionManager;    
    }

   public function getConfig()
   {
      //$this->coreSession->setVIErequestData(1);  // Set Session Data
      //$this->coreSession->unsVIErequestData();   // Unset Session Data
      //$this->coreSession->getVIErequestData();

      if($this->coreSession->getVIErequestData()){  
            $output['session_VIEUserData'] = true;
        } else {
            $output['session_VIEUserData'] = false;
       }       
       return $output;
   }
}
  • I tried the way you also tried, but i am not able to access window.checkoutConfig.session_VIEUserData in my js file,Any help highly appreciated – Mujahidh Feb 5 at 10:32
1

If you want to pass your PHP SESSION variable data in your JS then please follow below steps :

  1. Create di.xml file here in your custom module

app/code/Vendor/Module/etc/di.xml

Content for this file is..

<?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\Model\DefaultConfigProvider" type="Vendor\Module\Model\DefaultConfigProvider" />
</config>
  1. Create DefaultConfigProvider.php file here

app/code/Vendor/Module/Model/DefaultConfigProvider.php

Content for this file is..

<?php

namespace Vendor\Module\Model;

use Magento\Store\Model\ScopeInterface;
use Magento\Framework\Session\SessionManager;

class DefaultConfigProvider extends \Magento\Checkout\Model\DefaultConfigProvider
{
    /**
     * @var SessionManager
    */
    private $coreSession;

    /**
     * @param SessionManager $sessionManager
     */
    public function __construct(
        SessionManager $sessionManager
    ) {
        $this->coreSession = $sessionManager;    
    }

    public function getConfig()
    {
        $output = parent::getConfig();
        if($this->coreSession->getVIErequestData()){
            $output['session_VIEUserData'] = true;
        }else{
            $output['session_VIEUserData'] = false;
        }

        return $output;
    }
}

Now run below command once

php bin/magento setup:upgrade
php bin/magento cache:clean
php bin/magento cache:flush

Now you can use below line in your JS file to get PHP SESSION variable data there

console.log(window.checkoutConfig.session_VIEUserData);
  • If you want to get session data for all pages in your mixin js file then you can do below thing in your JS file
define([
    'uiComponent',
    'Magento_Customer/js/customer-data',
    'jquery',
    'ko',
    'underscore',
    'sidebar',
    'mage/translate',
    'mage/dropdown'
], function (Component, customerData, $, ko, _) {
    'use strict';

    var mixin = {
        isButtonEnable: function () {
            console.log("isButtonEnable calling");

            var baseUrl = window.BASE_URL;
            var redirectUrl = baseUrl + 'frontName/index/index/';
            var sessionData;

            $.ajax({
                url: redirectUrl,
                type: 'POST',
                async: false,
                dataType: 'json',
                success: function(data, status, xhr) {
                    if(data.success){
                        sessionData = data.sessionData;
                    }
                },
                error: function (xhr, status, errorThrown) {
                    console.log(errorThrown);
                }
            });

            /*You can add your condition here based on your requirements.*/
            //console.log(window.checkoutConfig.session_VIEUserData);
            //You can use 'sessionData' in your condition
            if(window.checkoutConfig.session_VIEUserData){
                return true; //hide button
            }else {
                return false;  //show button
            }
        }
    };

    return function (target) {
        return target.extend(mixin);
    };
});

Now you need to create one controller action, because we have added one ajax call here

So create your frontend router and create one controller file

Content for controller file is..

<?php

namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\Session\SessionManager;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $coreSession;

    public function __construct(
        Context $context,
        SessionManager $sessionManager
        ) {
        $this->coreSession = $sessionManager;
        parent::__construct($context);
    }

    public function execute()
    {
        $sessionData = ($this->coreSession->getVIErequestData()) ? true : false;
        return $this->resultFactory
        ->create(\Magento\Framework\Controller\ResultFactory::TYPE_JSON)
        ->setData([
            'success' => true,
            'sessionData' => $sessionData
        ]);
    }
}

You can follow this module as well. Download

Hope this will help!

| improve this answer | |
  • Let me know if this works for you then – Kishan Savaliya Nov 18 '19 at 4:31
  • sure @krishan I am checking now will let you know. one small query console.log(window.checkoutConfig.session_VIEUserData); is this will load on all pages (or) only on cart & checkout page? – Nagaraju K Nov 18 '19 at 6:02
  • All pages means checkout and cart page ? or you want this on any other pages as well ? – Kishan Savaliya Nov 18 '19 at 6:03
  • other pages as well. – Nagaraju K Nov 18 '19 at 6:05
  • Give me few mins I'll update my answer – Kishan Savaliya Nov 18 '19 at 6:14
0

There is one more way to hide proceed to checkout button if the session variable to set. which will affect the cart page proceed to checkout buttons at minicar at section & bottom of the page.

app/code/Vendor/ModuleName/etc/frontend/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">
  <type name="Magento\Checkout\Helper\Data">
       <plugin name="canOnepageCheckoutData" type="Vendor\ModuleName\Plugin\ProceedToCheckoutButton" disabled="false"/>
   </type>  
</config>

app/code/Vendor/ModuleName/Plugin/ProceedToCheckoutButton.php

<?php
namespace Vendor\ModuleName\Plugin;
use Magento\Framework\Session\SessionManager;
/**
 * Class ProceedToCheckoutButton
 * @package Vendor\ModuleName\Plugin
 */
class ProceedToCheckoutButton
{

     /**
     * @var SessionManager
    */
    private $coreSession;

     /**
     * @param SessionManager $sessionManager
     */
    public function __construct(
        SessionManager $sessionManager
    ) {
        $this->coreSession = $sessionManager;    
    }

    /**
     * 
     * @param $subject
     * @param $result
     * @return mixed
     */
    public function afterCanOnepageCheckout(\Magento\Checkout\Helper\Data $subject, $result)
    {
        $writer = new \Zend\Log\Writer\Stream(BP.'/var/log/magento4.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);        
        $logger->info("CanOnepageCheckout plugin has been calling");

        $this->coreSession->setVIErequestData(123);//Set
        //$this->coreSession->unsVIErequestData(); //unset
        if($result){
         if($this->coreSession->getVIErequestData()) {
            return false;
         }
         return $result;
        }

    }
}

php bin/magento setup:di:compile php bin/magento

setup:static-content:deploy -f

| improve this answer | |

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.