Magento 2 Cache – Why PHP Code is Cached on Listing Page

cachemagento2

I have built in full page cache enabled in Magento.

I have added following code in app/design/frontend/Vendor/Module/Magento_Catalog/templates/product/list.phtml which shows whether an item is already in wishlist or not

<?php $wishlistHelper = $this->helper('Magento\Wishlist\Helper\Data'); 
// other code
foreach ($_productCollection as $_product): 
$_in_wishlist = false;
    foreach ($wishlistHelper->getWishlistItemCollection() as $_wishlist_item){
        if(($_product->getId() == $_wishlist_item->getProduct()->getId()) && $customerLoggedin) {
             $_in_wishlist = true;
        }
       }
var_dump($_in_wishlist);
endforeach;
?>

Now I have some code on the same page which adds product to wishlist via Ajax call which works fine.

If I reload the page after product is added to wishlist, above code shows bool(false) but when I clean cache by running bin/magento cache:clean it shows the correct value which is bool(true).

Why this code is getting cached and how to fix it?

Best Answer

When FPC is enabled, prefer always factory method. Factory method will create new object. So, it will return always updated data :

By Object Manager :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$wishlist = $objectManager->create('\Magento\Wishlist\Model\Wishlist');
$wishlist_collection = $wishlist->loadByCustomerId("customer_id", true)->getItemCollection();

By Factory Method :

protected $_wishlistFactory;

public function __construct(
    \Magento\Wishlist\Model\WishlistFactory $wishlistFactory
){
    $this->_wishlistFactory = $wishlistFactory;
}

public function yourFunction()
{
    $wishlist = $this->_wishlistFactory->create();
    $wishlist_collection = $wishlist->loadByCustomerId("customer_id", true)->getItemCollection();
}
Related Topic