0

I want to make own recently viewed widget, cause this standard loads items with javascirpt (I want to have items directly). So I made this code, based on other posts:

namespace AA\WidgetRecently\Block\Widget;

use Magento\Framework\View\Element\Template;
use Magento\Widget\Block\BlockInterface;

class Data extends Template implements BlockInterface
{
  protected $_template = "widget/recently.phtml";

  protected $recentlyViewed;

  public function __construct(
      \Magento\Catalog\Block\Product\Context $context,
      \Magento\Reports\Block\Product\Viewed $recentlyViewed,
      \Magento\Catalog\Block\Product\ImageBuilder $imageBuilder,
      array $data = []
      ) {
      $this->recentlyViewed = $recentlyViewed;
      $this->imageBuilder = $imageBuilder;

  parent::__construct( $context, $data );
  }

  public function getRecentlyViewedProducts(){
      return $this->recentlyViewed->getItemsCollection();
  }  

}

and this code in template

<?php if ($exist = ($block->getRecentlyViewedProducts() && $block->getRecentlyViewedProducts()->getSize())): ?>

returns nothing, is false.

But when I add block in layout file:

    <block class="Magento\Reports\Block\Product\Widget\Viewed" name="recently_viewed" cacheable="false" template="Magento_Reports::widget/viewed/content/viewed_grid.phtml">
      <action method="setPageSize">
          <argument name="page_size" xsi:type="number">5</argument>
      </action>
    </block>

the widget phtml is working and shows products (and obviously recently products are repeated cause of adding block in xml layout).

Why widget is not working, it looks like something more should be initialized?

1

I think I've found the problem. This is something about cache (of cms page) and visitor detection. Probably when pages are cached user (visitor) session is not set. In Magento\Reports\Model\ResourceModel\Product\Index\Collection\AbstractCollection there is function _getWhereCondition which sets condition $condition['visitor_id'] = $this->_customerVisitor->getId();. Visitior is empty so sql query condition is idx_table.visitor_id = '' so no rows are returned.

Best solution is to set visitor, but I have no idea how?

I made workaround by:

  • adding to layout xml recently viewed block with empty phtml <block class="Magento\Reports\Block\Product\Widget\Viewed" name="recently_viewed" cacheable="false" template="Magento_Reports::widget/viewed/content/dummy.phtml" after="hg.view.seobox">. This will correctly set recently viewed collection
  • widget block's code remains like in my question and now it is returning data. I have only add $this->recentlyViewed->setData('page_size', 15);

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.