Php Magento 2-包含块时获取当前搜索页面上的结果数
我正在尝试访问\Magento\CatalogSearch\Block\Result中的getResultCount() 我创建了以下块Php Magento 2-包含块时获取当前搜索页面上的结果数,php,magento2,Php,Magento2,我正在尝试访问\Magento\CatalogSearch\Block\Result中的getResultCount() 我创建了以下块 class GetSearch extends \Magento\Framework\View\Element\Template { protected $_pageTitle; protected $_result; public function __construct(\Magento\Framework\View\Element
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();
}
}
当我呼叫
我收到以下错误:未捕获错误:调用布尔值上的成员函数getLoadedProductCollection()
我想我这样做是错误的,我需要访问包含搜索结果的当前对象,但我有点迷路了
执行此操作的最佳方法是什么?我终于找到了答案,它是使用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();
}
}