Try to use Magento\Cms\Model\BlockRepository
to get block by ID, like this:
/**
* @var \Magento\Cms\Model\BlockRepository
*/
protected $blockRepository;
/**
* @param \Magento\Cms\Model\BlockRepository $blockRepository
*/
public function __construct(
\Magento\Cms\Model\BlockRepository $blockRepository
) {
$this->blockRepository = $blockRepository;
}
public function getBlockById($id, $storeId)
{
$block = $this->blockRepository->getById($id)
->setStoreId($storeId);
return $block;
}
In addition you can use the method getList()
to get block like this:
/**
* @var \Magento\Cms\Model\BlockRepository
*/
protected $blockRepository;
/**
* @var \Magento\Framework\Api\FilterBuilder
*/
protected $filterBuilder;
/**
* @var \Magento\Framework\Api\Search\FilterGroup
*/
protected $filterGroup;
/**
* @var \Magento\Framework\Api\SearchCriteriaInterface
*/
protected $searchCriteria;
/**
* @param \Magento\Cms\Model\BlockRepository $blockRepository
* @param \Magento\Framework\Api\SearchCriteriaInterface $criteria
* @param \Magento\Framework\Api\Search\FilterGroup $filterGroup
* @param \Magento\Framework\Api\FilterBuilder $filterBuilder
*/
public function __construct(
\Magento\Cms\Model\BlockRepository $blockRepository,
\Magento\Framework\Api\SearchCriteriaInterface $criteria,
\Magento\Framework\Api\Search\FilterGroup $filterGroup,
\Magento\Framework\Api\FilterBuilder $filterBuilder
) {
$this->blockRepository = $blockRepository;
$this->searchCriteria = $criteria;
$this->filterGroup = $filterGroup;
$this->filterBuilder = $filterBuilder;
}
/**
* @return \Magento\Cms\Model\Block|null
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
protected function getBlockData()
{
$block = null;
$storeId = 0;
$blockId = 'test-block';
$this->filterGroup->setFilters([
$this->filterBuilder->create()
->setField('store_id')
->setValue($storeId)
->setConditionType('eq'), // default value
$this->filterBuilder->create()
->setField('identifier')
->setValue($blockId),
]);
$this->searchCriteria->setFilterGroups([$this->filterGroup]);
$blocks = $this->blockRepository->getList($this->searchCriteria);
if ($blocks->getItems()) {
/** @var \Magento\Cms\Model\Block $block */
$block = $this->blockRepository->getById($blockId);
}
return $block;
}
The getList()
result should look like this:
and block looks as usual: