2017-09-03 78 views
2

我试图访问getResultCount时获取当前搜索页面结果的数量()在\ Magento的\ CatalogSearch \块\结果Magento的2 - 包括块

我有以下块创建。

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

} 

当我打电话<?=$block->getSearchResults();?>

我收到以下错误:未捕获的错误:调用一个成员函数getLoadedProductCollection()布尔

我想我会对此错误的方式以某种方式需要访问包含搜索结果的当前对象,但我有点失落。

什么是这样做的最佳方法是什么?

回答

0

我终于找到了答案,它是使用QueryFactory返回查询模型的实例。

希望这将有助于未来的人!

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

}