Why php code is getting cached in Magento 2 listing page?












1














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('MagentoWishlistHelperData'); 
// 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?










share|improve this question






















  • echo anything else, first confirm you are editing correct file ?
    – Wajahat Bashir
    Dec 26 '18 at 11:16










  • Yes, I am modifying the correct file.
    – amitshree
    Dec 26 '18 at 12:05
















1














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('MagentoWishlistHelperData'); 
// 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?










share|improve this question






















  • echo anything else, first confirm you are editing correct file ?
    – Wajahat Bashir
    Dec 26 '18 at 11:16










  • Yes, I am modifying the correct file.
    – amitshree
    Dec 26 '18 at 12:05














1












1








1







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('MagentoWishlistHelperData'); 
// 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?










share|improve this question













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('MagentoWishlistHelperData'); 
// 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?







magento2 cache






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 26 '18 at 10:59









amitshreeamitshree

3,019103776




3,019103776












  • echo anything else, first confirm you are editing correct file ?
    – Wajahat Bashir
    Dec 26 '18 at 11:16










  • Yes, I am modifying the correct file.
    – amitshree
    Dec 26 '18 at 12:05


















  • echo anything else, first confirm you are editing correct file ?
    – Wajahat Bashir
    Dec 26 '18 at 11:16










  • Yes, I am modifying the correct file.
    – amitshree
    Dec 26 '18 at 12:05
















echo anything else, first confirm you are editing correct file ?
– Wajahat Bashir
Dec 26 '18 at 11:16




echo anything else, first confirm you are editing correct file ?
– Wajahat Bashir
Dec 26 '18 at 11:16












Yes, I am modifying the correct file.
– amitshree
Dec 26 '18 at 12:05




Yes, I am modifying the correct file.
– amitshree
Dec 26 '18 at 12:05










2 Answers
2






active

oldest

votes


















2














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 = MagentoFrameworkAppObjectManager::getInstance();
$wishlist = $objectManager->create('MagentoWishlistModelWishlist');
$wishlist_collection = $wishlist->loadByCustomerId("customer_id", true)->getItemCollection();


By Factory Method :



protected $_wishlistFactory;

public function __construct(
MagentoWishlistModelWishlistFactory $wishlistFactory
){
$this->_wishlistFactory = $wishlistFactory;
}

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





share|improve this answer





















  • I tried the object manager way but still it is not reflecting without clearing cache.
    – amitshree
    Dec 26 '18 at 12:29










  • I just added object manager answer for reference. For better practise use Factory Method. It should be work.
    – Rohan Hapani
    Dec 26 '18 at 12:41










  • I have added echo "test"; on the top of list.phtml. I changed it to echo "test 2";. Which is not reflecting if I do not clear cache.
    – amitshree
    Dec 27 '18 at 9:46



















0














This issue is because of enabled full page cache on listing pages.



Due to enabled full page cache, content of listing page is considered as public content. Public content is stored server side in your reverse proxy cache storage (e.g., file system, database, Redis, or Varnish) and same data is available to multiple customers.



To fix the issue I have created a custom controller to provide wishlist data of current user. Using ajax call I got the data from this controller which gives refreshed wishlist data and not cached one.



Sharing my controller code which might be helpful to someone:



<?php

namespace VendorModuleControllerIndex;

class Wishlist extends MagentoFrameworkAppActionAction {

public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoWishlistHelperData $wishlistHelper,
MagentoFrameworkControllerResultJsonFactory $jsonFactory
) {
parent::__construct($context);
$this->wishlistHelper = $wishlistHelper;
$this->jsonFactory = $jsonFactory;
}

public function execute() {
$result = $this->jsonFactory->create();
$data = $this->wishlistHelper->getWishlistItemCollection()->getData();

return $result->setData(['status' => 200, 'items' => $data]);
}
}


And added following code in list.phtml



<script>
require(['jquery'], function($){
$.ajax({
url: '<?php echo $this->getUrl('catalogchanges/index/wishlist') ?>',
method: 'get',
dataType: 'json',
success: function(data) {
var wislistAddesCheckData = data;
var itemLenth = wislistAddesCheckData.items.length;
for(i=0;i<itemLenth; i++){
var wislistAddedProductId = wislistAddesCheckData.items[i].product_id;
$(".product-id"+wislistAddedProductId).addClass('in-wishlist');
}
}
});
});
</script>





share|improve this answer





















    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "479"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f255810%2fwhy-php-code-is-getting-cached-in-magento-2-listing-page%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    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 = MagentoFrameworkAppObjectManager::getInstance();
    $wishlist = $objectManager->create('MagentoWishlistModelWishlist');
    $wishlist_collection = $wishlist->loadByCustomerId("customer_id", true)->getItemCollection();


    By Factory Method :



    protected $_wishlistFactory;

    public function __construct(
    MagentoWishlistModelWishlistFactory $wishlistFactory
    ){
    $this->_wishlistFactory = $wishlistFactory;
    }

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





    share|improve this answer





















    • I tried the object manager way but still it is not reflecting without clearing cache.
      – amitshree
      Dec 26 '18 at 12:29










    • I just added object manager answer for reference. For better practise use Factory Method. It should be work.
      – Rohan Hapani
      Dec 26 '18 at 12:41










    • I have added echo "test"; on the top of list.phtml. I changed it to echo "test 2";. Which is not reflecting if I do not clear cache.
      – amitshree
      Dec 27 '18 at 9:46
















    2














    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 = MagentoFrameworkAppObjectManager::getInstance();
    $wishlist = $objectManager->create('MagentoWishlistModelWishlist');
    $wishlist_collection = $wishlist->loadByCustomerId("customer_id", true)->getItemCollection();


    By Factory Method :



    protected $_wishlistFactory;

    public function __construct(
    MagentoWishlistModelWishlistFactory $wishlistFactory
    ){
    $this->_wishlistFactory = $wishlistFactory;
    }

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





    share|improve this answer





















    • I tried the object manager way but still it is not reflecting without clearing cache.
      – amitshree
      Dec 26 '18 at 12:29










    • I just added object manager answer for reference. For better practise use Factory Method. It should be work.
      – Rohan Hapani
      Dec 26 '18 at 12:41










    • I have added echo "test"; on the top of list.phtml. I changed it to echo "test 2";. Which is not reflecting if I do not clear cache.
      – amitshree
      Dec 27 '18 at 9:46














    2












    2








    2






    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 = MagentoFrameworkAppObjectManager::getInstance();
    $wishlist = $objectManager->create('MagentoWishlistModelWishlist');
    $wishlist_collection = $wishlist->loadByCustomerId("customer_id", true)->getItemCollection();


    By Factory Method :



    protected $_wishlistFactory;

    public function __construct(
    MagentoWishlistModelWishlistFactory $wishlistFactory
    ){
    $this->_wishlistFactory = $wishlistFactory;
    }

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





    share|improve this 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 = MagentoFrameworkAppObjectManager::getInstance();
    $wishlist = $objectManager->create('MagentoWishlistModelWishlist');
    $wishlist_collection = $wishlist->loadByCustomerId("customer_id", true)->getItemCollection();


    By Factory Method :



    protected $_wishlistFactory;

    public function __construct(
    MagentoWishlistModelWishlistFactory $wishlistFactory
    ){
    $this->_wishlistFactory = $wishlistFactory;
    }

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






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Dec 26 '18 at 11:08









    Rohan HapaniRohan Hapani

    5,87721662




    5,87721662












    • I tried the object manager way but still it is not reflecting without clearing cache.
      – amitshree
      Dec 26 '18 at 12:29










    • I just added object manager answer for reference. For better practise use Factory Method. It should be work.
      – Rohan Hapani
      Dec 26 '18 at 12:41










    • I have added echo "test"; on the top of list.phtml. I changed it to echo "test 2";. Which is not reflecting if I do not clear cache.
      – amitshree
      Dec 27 '18 at 9:46


















    • I tried the object manager way but still it is not reflecting without clearing cache.
      – amitshree
      Dec 26 '18 at 12:29










    • I just added object manager answer for reference. For better practise use Factory Method. It should be work.
      – Rohan Hapani
      Dec 26 '18 at 12:41










    • I have added echo "test"; on the top of list.phtml. I changed it to echo "test 2";. Which is not reflecting if I do not clear cache.
      – amitshree
      Dec 27 '18 at 9:46
















    I tried the object manager way but still it is not reflecting without clearing cache.
    – amitshree
    Dec 26 '18 at 12:29




    I tried the object manager way but still it is not reflecting without clearing cache.
    – amitshree
    Dec 26 '18 at 12:29












    I just added object manager answer for reference. For better practise use Factory Method. It should be work.
    – Rohan Hapani
    Dec 26 '18 at 12:41




    I just added object manager answer for reference. For better practise use Factory Method. It should be work.
    – Rohan Hapani
    Dec 26 '18 at 12:41












    I have added echo "test"; on the top of list.phtml. I changed it to echo "test 2";. Which is not reflecting if I do not clear cache.
    – amitshree
    Dec 27 '18 at 9:46




    I have added echo "test"; on the top of list.phtml. I changed it to echo "test 2";. Which is not reflecting if I do not clear cache.
    – amitshree
    Dec 27 '18 at 9:46













    0














    This issue is because of enabled full page cache on listing pages.



    Due to enabled full page cache, content of listing page is considered as public content. Public content is stored server side in your reverse proxy cache storage (e.g., file system, database, Redis, or Varnish) and same data is available to multiple customers.



    To fix the issue I have created a custom controller to provide wishlist data of current user. Using ajax call I got the data from this controller which gives refreshed wishlist data and not cached one.



    Sharing my controller code which might be helpful to someone:



    <?php

    namespace VendorModuleControllerIndex;

    class Wishlist extends MagentoFrameworkAppActionAction {

    public function __construct(
    MagentoFrameworkAppActionContext $context,
    MagentoWishlistHelperData $wishlistHelper,
    MagentoFrameworkControllerResultJsonFactory $jsonFactory
    ) {
    parent::__construct($context);
    $this->wishlistHelper = $wishlistHelper;
    $this->jsonFactory = $jsonFactory;
    }

    public function execute() {
    $result = $this->jsonFactory->create();
    $data = $this->wishlistHelper->getWishlistItemCollection()->getData();

    return $result->setData(['status' => 200, 'items' => $data]);
    }
    }


    And added following code in list.phtml



    <script>
    require(['jquery'], function($){
    $.ajax({
    url: '<?php echo $this->getUrl('catalogchanges/index/wishlist') ?>',
    method: 'get',
    dataType: 'json',
    success: function(data) {
    var wislistAddesCheckData = data;
    var itemLenth = wislistAddesCheckData.items.length;
    for(i=0;i<itemLenth; i++){
    var wislistAddedProductId = wislistAddesCheckData.items[i].product_id;
    $(".product-id"+wislistAddedProductId).addClass('in-wishlist');
    }
    }
    });
    });
    </script>





    share|improve this answer


























      0














      This issue is because of enabled full page cache on listing pages.



      Due to enabled full page cache, content of listing page is considered as public content. Public content is stored server side in your reverse proxy cache storage (e.g., file system, database, Redis, or Varnish) and same data is available to multiple customers.



      To fix the issue I have created a custom controller to provide wishlist data of current user. Using ajax call I got the data from this controller which gives refreshed wishlist data and not cached one.



      Sharing my controller code which might be helpful to someone:



      <?php

      namespace VendorModuleControllerIndex;

      class Wishlist extends MagentoFrameworkAppActionAction {

      public function __construct(
      MagentoFrameworkAppActionContext $context,
      MagentoWishlistHelperData $wishlistHelper,
      MagentoFrameworkControllerResultJsonFactory $jsonFactory
      ) {
      parent::__construct($context);
      $this->wishlistHelper = $wishlistHelper;
      $this->jsonFactory = $jsonFactory;
      }

      public function execute() {
      $result = $this->jsonFactory->create();
      $data = $this->wishlistHelper->getWishlistItemCollection()->getData();

      return $result->setData(['status' => 200, 'items' => $data]);
      }
      }


      And added following code in list.phtml



      <script>
      require(['jquery'], function($){
      $.ajax({
      url: '<?php echo $this->getUrl('catalogchanges/index/wishlist') ?>',
      method: 'get',
      dataType: 'json',
      success: function(data) {
      var wislistAddesCheckData = data;
      var itemLenth = wislistAddesCheckData.items.length;
      for(i=0;i<itemLenth; i++){
      var wislistAddedProductId = wislistAddesCheckData.items[i].product_id;
      $(".product-id"+wislistAddedProductId).addClass('in-wishlist');
      }
      }
      });
      });
      </script>





      share|improve this answer
























        0












        0








        0






        This issue is because of enabled full page cache on listing pages.



        Due to enabled full page cache, content of listing page is considered as public content. Public content is stored server side in your reverse proxy cache storage (e.g., file system, database, Redis, or Varnish) and same data is available to multiple customers.



        To fix the issue I have created a custom controller to provide wishlist data of current user. Using ajax call I got the data from this controller which gives refreshed wishlist data and not cached one.



        Sharing my controller code which might be helpful to someone:



        <?php

        namespace VendorModuleControllerIndex;

        class Wishlist extends MagentoFrameworkAppActionAction {

        public function __construct(
        MagentoFrameworkAppActionContext $context,
        MagentoWishlistHelperData $wishlistHelper,
        MagentoFrameworkControllerResultJsonFactory $jsonFactory
        ) {
        parent::__construct($context);
        $this->wishlistHelper = $wishlistHelper;
        $this->jsonFactory = $jsonFactory;
        }

        public function execute() {
        $result = $this->jsonFactory->create();
        $data = $this->wishlistHelper->getWishlistItemCollection()->getData();

        return $result->setData(['status' => 200, 'items' => $data]);
        }
        }


        And added following code in list.phtml



        <script>
        require(['jquery'], function($){
        $.ajax({
        url: '<?php echo $this->getUrl('catalogchanges/index/wishlist') ?>',
        method: 'get',
        dataType: 'json',
        success: function(data) {
        var wislistAddesCheckData = data;
        var itemLenth = wislistAddesCheckData.items.length;
        for(i=0;i<itemLenth; i++){
        var wislistAddedProductId = wislistAddesCheckData.items[i].product_id;
        $(".product-id"+wislistAddedProductId).addClass('in-wishlist');
        }
        }
        });
        });
        </script>





        share|improve this answer












        This issue is because of enabled full page cache on listing pages.



        Due to enabled full page cache, content of listing page is considered as public content. Public content is stored server side in your reverse proxy cache storage (e.g., file system, database, Redis, or Varnish) and same data is available to multiple customers.



        To fix the issue I have created a custom controller to provide wishlist data of current user. Using ajax call I got the data from this controller which gives refreshed wishlist data and not cached one.



        Sharing my controller code which might be helpful to someone:



        <?php

        namespace VendorModuleControllerIndex;

        class Wishlist extends MagentoFrameworkAppActionAction {

        public function __construct(
        MagentoFrameworkAppActionContext $context,
        MagentoWishlistHelperData $wishlistHelper,
        MagentoFrameworkControllerResultJsonFactory $jsonFactory
        ) {
        parent::__construct($context);
        $this->wishlistHelper = $wishlistHelper;
        $this->jsonFactory = $jsonFactory;
        }

        public function execute() {
        $result = $this->jsonFactory->create();
        $data = $this->wishlistHelper->getWishlistItemCollection()->getData();

        return $result->setData(['status' => 200, 'items' => $data]);
        }
        }


        And added following code in list.phtml



        <script>
        require(['jquery'], function($){
        $.ajax({
        url: '<?php echo $this->getUrl('catalogchanges/index/wishlist') ?>',
        method: 'get',
        dataType: 'json',
        success: function(data) {
        var wislistAddesCheckData = data;
        var itemLenth = wislistAddesCheckData.items.length;
        for(i=0;i<itemLenth; i++){
        var wislistAddedProductId = wislistAddesCheckData.items[i].product_id;
        $(".product-id"+wislistAddedProductId).addClass('in-wishlist');
        }
        }
        });
        });
        </script>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        amitshreeamitshree

        3,019103776




        3,019103776






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f255810%2fwhy-php-code-is-getting-cached-in-magento-2-listing-page%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            An IMO inspired problem

            Management

            Has there ever been an instance of an active nuclear power plant within or near a war zone?