1

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;
    }
);

2 Answers 2

0

Set 'cache_lifetime' => null

0

This is because of the FPC, you have to add cacheable = "false" in your block but it is not recommended.

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

If you want to even surpass the FPC you have to add these labels via knockout JS or Ajax

Tell me if its clear? for you?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.