0

I am creating an extension for displaying labels in product page and listing page. Everything works fine except the cache issue. If I set the status to inactive, then the labels will display in the frontend until I clear the cache. How can I automatically display/off these?

Here is my code.

Layout XML

 <referenceContainer name="content">
            <block class="Company\ProductLabel\Block\Productlabel" name="product.label" template="Company_ProductLabel::productlabel.phtml"  />
 </referenceContainer>

Phtml

<?php 
if($block->isActive()):
    $productStickerBlock = $block->setStickerHTML();
?>

<script type="text/x-magento-init">
    {
        "*":{
            "viewPageSticker":{
                "imageTag": {
                  "imagePath": "<?php echo $productStickerBlock; ?>"
                }
            }
        }
    }
</script>

<?php endif;  ?>

Block

use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Framework\DataObject\IdentityInterface;


class Productlabel extends \Magento\Framework\View\Element\Template 
{
    protected $product = null;

    protected $coreRegistry;
    protected $productFactory;
    protected $collectionFactory;
    private $scopeConfig;
    private $_regularPrice;
    private $_finalPrice;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Company\ProductLabel\Model\ResourceModel\Productlabel\Grid\CollectionFactory $collectionFactory,
        array $data = []
    ) {
        $this->scopeConfig = $context->getScopeConfig();
        $this->coreRegistry = $registry;
        $this->productFactory = $productFactory;
        $this->collectionFactory = $collectionFactory;
        parent::__construct($context, $data);
        $this->addData([
                'cache_lifetime' => 360
            ]);

    }

    public function getCacheKeyInfo()
    {
        $productId = $this->_getProduct()?$this->_getProduct()->getId() : null;
        $mode = 'cat' ;
        if($productId) {
          $mode = 'prod';
        }

        return [
            $this->_storeManager->getStore()->getId(),
            $this->_design->getDesignTheme()->getId(),
            $mode,
            rand(),
            $productId
        ];
    }



    protected function _getProduct()
    {
        if (!$this->product) {
            $this->product = $this->coreRegistry->registry('product');
        }

        return $this->product;
    }

    public function isActive()
    {
       $active = $this->scopeConfig->getValue(
            'company_productlabel/general/enable',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        if ($active) {
            return true;
        }
        return false;
    }
     public function setStickerHTML()
    {
        $now = new \DateTime();

        $collection = $this->collectionFactory->create()
                      ->addFieldToFilter('status', 1)
                      ->addFieldToFilter( array('from_date'),   array( array(   array('lteq' => $now->format('Y-m-d H:i:s')),  array('null' => true))))
                      ->addFieldToFilter( array('to_date'),   array( array(  array('gteq' => $now->format('Y-m-d H:i:s')),  array('null' => true))))
                       ->addFieldToFilter('product_id', $this->_getProduct()->getId());

        $html = '';
        if($collection->getSize()) {
            $discount =  '' ;
            $html = "";
            foreach($collection as $label){                 
                $html .= "<div class='productsticker-wrapper ".$label->getLabelPosition()."'><img class='productlabelImage' src='".$this->getUrl('pub/media').$label->getImagePath()."' /></div>";             
            }
        }
        return $html;
    }


}

Require Js

var config = {
    map: {
        '*': {
            viewPageSticker: 'Company_ProductLabel/js/viewPageSticker'
        }
    }
};

JS File

define(
    [
        'jquery'
    ],
    function ($) {
        $.widget(
            'company.viewPageSticker',
            {
                _create: function () {
                    var self = this;
                    $(".product.media").append(self.options.imageTag.imagePath);
                }
            }
        );
        return $.company.viewPageSticker;
    }
);
0

Set 'cache_lifetime' => null

|improve this answer|||||
-1

You can disable the particular block cache using cacheable attribute:

<block class="Company\ProductLabel\Block\Productlabel" name="product.label" template="Company_ProductLabel::productlabel.phtml" cacheable="false" />

NOTE: You may have some performance problem after this because this will make the whole page non-cacheable.

One more solution is that, you can use ttl for cache:

<block class="Company\ProductLabel\Block\Productlabel" name="product.label" template="Company_ProductLabel::productlabel.phtml" cacheable="false" ttl="900"/>

You can also add this function into you block file:

public function getCacheLifetime()
{
    return null;
}
|improve this answer|||||
  • ttl is not working – Jancy Abraham May 27 '19 at 7:06
  • flush cache and deploy new cotent, try both one by one, it should work because I am using the same. I have added one more solution – Saphal Jha May 27 '19 at 7:06
  • First solution will work, but it will disable the Caching for the whole page – Jancy Abraham May 27 '19 at 7:15
  • No, it will disable the cache for that perticular block only, in which you adde that code, i.e. for only : Company\ProductLabel\Block\Productlabel – Saphal Jha May 27 '19 at 7:29
  • The TTL solution is not working. 3rd solution also have performance issue. Please check this url: interactiv4.com/e-commerce-en/… It says the cacheable="false" attribute will make the whole page non cacheable. – Jancy Abraham May 27 '19 at 8:04

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.