Question

I have used \Magento\Checkout\Model\Session for get quote id and store my custom value in this. but its return every time empty session. when FPC on or customer not logged in.

I have found out some solution but no luck with this. My block is placed in header section so its not good to used cacheable="false". Because its turn off all my pages cache.

Any other solution?

Edited

$checkoutSession = $objectManager->create('Magento\Checkout\Model\Session');
$resultPageFactory = $objectManager->create('Magento\Framework\View\Result\PageFactory');
$quoteId = $checkoutSession->getQuoteId();
Was it helpful?

Solution

Should not try to use cacheable="false" in your header because it will disable cache all pages. Use the Ajax way.

For example,

Because I cannot find a better way (it should be layout xml) to set the template for Html header block. So, I tried to override it.

app/code/Vendor/Theme/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">
    <preference for="Magento\Theme\Block\Html\Header"
                type="Vendor\Theme\Block\Html\Header" />
</config>

app/code/Vendor/Theme/Block/Html/Header.php

<?php

namespace Vendor\Theme\Block\Html;

class Header extends \Magento\Theme\Block\Html\Header
{
    /**
     * Current template name
     *
     * @var string
     */
    protected $_template = 'Vendor_Theme::html/header.phtml';

}

app/code/Vendor/Theme/view/frontend/templates/html/header.phtml

Add these code lines:

.......
<li class="show-random-number"
    data-mage-init='{"Vendor_Theme/js/header/radom": {"ajaxUrl":
    "<?php echo $block->getUrl('vendor_theme/ajax/random')?>"}}'>
</li>

app/code/Vendor/Theme/view/frontend/web/js/header/radom.js

define([
    'jquery'
], function ($) {
    'use strict';

    /**
     * @param {String} url
     * @param {*} element
     */
    function processData(url, element) {
        $.ajax({
            url: url,
            dataType: 'json'
        }).done(function (res) {
            $(element).html("Random value: " + res.random);
        }).complete(function () {

        });
    }

    return function (config, element) {
        processData(config.ajaxUrl, element);
    };
});

app/code/Vendor/Theme/etc/frontend/routes.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="vendor_theme" frontName="vendor_theme">
            <module name="Vendor_Theme" />
        </route>
    </router>
</config>

app/code/Vendor/Theme/Controller/Ajax/Random.php

<?php

namespace Vendor\Theme\Controller\Ajax;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\JsonFactory;

class Random extends Action
{
    /**
     * @var JsonFactory
     */
    protected $jsonFactory;

    /**
     * Random constructor.
     * @param Context $context
     * @param JsonFactory $jsonFactory
     */
    public function __construct(
        Context $context,
        JsonFactory $jsonFactory
    ) {
        $this->jsonFactory = $jsonFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        $response = [
            'errors' => false,
            'random' => rand()
        ];

        /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
        $resultJson = $this->jsonFactory->create();
        return $resultJson->setData($response);
    }
}

Remember to create module.xml and registration.php. Clear your Magento Cache. We can see the result.

enter image description here

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