简体   繁体   English

Magento 2 - 在包含块时获取当前搜索页面上的结果数

[英]Magento 2 - Get number of results on current search page when including a block

I'm trying to access getResultCount() in \\Magento\\CatalogSearch\\Block\\Result 我正在尝试访问\\ Magento \\ CatalogSearch \\ Block \\ Result中的getResultCount()

I have the following block created. 我创建了以下块。

class GetSearch extends \Magento\Framework\View\Element\Template
{
    protected $_pageTitle;
    protected $_result;
    public function __construct(\Magento\Framework\View\Element\Template\Context $context,\Magento\Framework\View\Page\Title $pageTitle,
        \Magento\CatalogSearch\Block\Result $result)
    {
        $this->_pageTitle = $pageTitle;  
        $this->_result = $result;
        parent::__construct($context);
    }
    public function getTitle()
    {
        return $this->_pageTitle->getShort();
    }
     public function getSearchResults()
    {
        return $this->_result->getResultCount();
    }

}

When I call <?=$block->getSearchResults();?> 当我调用<?=$block->getSearchResults();?>

I receive the following error: Uncaught Error: Call to a member function getLoadedProductCollection() on boolean 我收到以下错误:未捕获错误:在布尔值上调用成员函数getLoadedProductCollection()

I think I'm going about this the wrong way and somehow need to access the current object that contains the search results but I'm a little lost. 我想我会以错误的方式解决这个问题,并且不知何故需要访问包含搜索结果的当前对象,但我有点迷失。

What's the best method of doing this? 这样做的最佳方法是什么?

I have finally found the answer and it is to use the QueryFactory to return the instance of the Query model. 我终于找到了答案,它是使用QueryFactory返回Query模型的实例。

Hopefully this will help someone in the future! 希望这将有助于未来的人!

class GetSearch extends \Magento\Framework\View\Element\Template
{
    protected $_pageTitle;
    protected $_query;
    public function __construct(\Magento\Framework\View\Element\Template\Context $context,\Magento\Framework\View\Page\Title $pageTitle,
        \Magento\Search\Model\QueryFactory $query)
    {
        $this->_pageTitle = $pageTitle;  
        $this->_query = $query;
        parent::__construct($context);
    }
    public function getTitle()
    {
        return $this->_pageTitle->getShort();
    }

    public function getSearchResults()
    {

       return $this->_query->get()->getNumResults();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM