2017-09-03 75 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(); 
    } 

}