I have created a custom block where I am showing the number of items in the cart and also loggedin the customer name. I am getting correct count and customer name on checkout page.But not on any other pages such as Product page, home page etc. This is because I have enabled full page caching. If I disable FPC then everything works fine. But I want to keep FPC and also need to show this count on other pages. How it can be done? I have already tried many codes like $this->_isScopePrivate = true; in constructor. But it's not working. I am using Magento 2.3.1. Below is sample code:
class ShoppingCart extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Checkout\Model\Session $checkoutSession,
array $data = []
) {
$this->_checkoutSession = $checkoutSession;;
parent::__construct($context, $data);
$this->_isScopePrivate = true;
}
/**
* Get quote object associated with cart. By default it is current customer session quote
*
* @return \Magento\Quote\Model\Quote
*/
public function getQuoteData()
{
$this->_checkoutSession->getQuote();
if (!$this->hasData('quote')) {
$this->setData('quote', $this->_checkoutSession->getQuote());
}
return $this->_getData('quote');
}
public function getMyCustomMethod(){
return "test function callecd";
}
}
and calling in logo.phtml page as.
$blockObj= $block->getLayout()->createBlock('Rbj\Customer\Block\ShoppingCart');
$quote = $blockObj->getQuoteData();
$itemsCount = $quote->getItemsCount();
$itemsCount = $blockObj->getMyCustomMethod();
Please advice. Thanks in advance.
-
You can make that specific block cache disable.Ravi Soni– Ravi Soni2019年06月27日 13:21:39 +00:00Commented Jun 27, 2019 at 13:21
-
Yes, we can. But then full page caching does not work for all pages.Sameer– Sameer2019年06月27日 13:43:36 +00:00Commented Jun 27, 2019 at 13:43
-
Adding below line in xml file prevents full page cache work. <block class="Rbj\Customer\Block\ShoppingCart" name="customBlock" cacheable="false"/>Sameer– Sameer2019年06月27日 13:44:26 +00:00Commented Jun 27, 2019 at 13:44
1 Answer 1
Magento 2 has special system for display personal/private customer data on the cachable pages.
Shortly: magento use additional ajax query to retrieve all needed private data (including data you needed). Than you can use this data from js.
In the Luma theme the minicart works using this way.
Here is additional query to private data:
Here is layout for minicart:
vendor/magento/module-checkout/view/frontend/layout/default.xml
Block
Magento\Checkout\Block\Cart\Sidebar
has inside js-layout which conteins js-components.
You can find them in vendor/magento/module-checkout/view/frontend/web
-
Can you demonstrate?Dominic Pixie– Dominic Pixie2019年06月27日 15:51:36 +00:00Commented Jun 27, 2019 at 15:51
-
I'll update my answersergei.sss– sergei.sss2019年06月27日 16:00:33 +00:00Commented Jun 27, 2019 at 16:00
Explore related questions
See similar questions with these tags.