Magento2 Get a list of all cms static blocks
-
15-04-2021 - |
Frage
I have created a new widget programatically and i would like to create a custom source model with dropdown values all the cms static blocks.
Is that possible? How can i get a list of all the static blocks ?
app/code/Ves/CustomWidget/etc/widget.xml
<parameter name="gender" xsi:type="select" source_model="Ves\CustomWidget\Model\Config\Source\StaticBlock" visible="true" sort_order="10" >
<label translate="true">Static Block</label>
</parameter>
And my Source Model
app/code/Ves/CustomWidget/Model/Config/Source/StaticBlock.php
namespace Ves\CustomWidget\Model\Config\Source;
class StaticBlock implements \Magento\Framework\Option\ArrayInterface
{
public function toOptionArray()
{
// Get all cms static blocks and return them by id/Title
// instead of hardcoded values
return [
['value' => 'static_block_id_1', 'label' => __('Static block Title 1')],
['value' => 'static_block_id_1', 'label' => __('Static block Title 1')]];
}
}
Lösung
Do a dependency injection of Magento\Cms\Model\BlockFactory class in your constructor
public function __construct(
...
\Magento\Cms\Model\BlockFactory $blockFactory,
...
) {
$this->_blockFactory = $blockFactory;
...
}
Then you can use the following code in your function to get the collection of blocks
$this->_blockFactory->create()->getCollection();
You can then use the above collection to iterate!
Andere Tipps
This is my version as a source model used inside system.xml file
<source_model>Vendor\Modulename\Model\Config\Source\CmsBlocks</source_model>
namespace Vendor\Modulename\Model\Config\Source;
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Data\OptionSourceInterface;
class CmsBlocks implements OptionSourceInterface
{
/**
* @var BlockRepositoryInterface
*/
protected BlockRepositoryInterface $blockRepository;
/**
* @var SearchCriteriaBuilder
*/
protected SearchCriteriaBuilder $searchCriteriaBuilder;
/**
* CmsBlocks constructor.
* @param BlockRepositoryInterface $blockRepository
* @param SearchCriteriaBuilder $searchCriteriaBuilder
*/
public function __construct(
BlockRepositoryInterface $blockRepository,
SearchCriteriaBuilder $searchCriteriaBuilder
) {
$this->blockRepository = $blockRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
}
/**
* Return array of options as value-label pairs
*
* @return array Format: array(array('value' => '<value>', 'label' => '<label>'), ...)
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function toOptionArray(): array
{
$searchCriteria = $this->searchCriteriaBuilder->create();
$cmsBlocks = $this->blockRepository->getList($searchCriteria)->getItems(); //LocalizedException
$arrResult = [];
foreach ($cmsBlocks as $block) {
$arrResult[] = ['value' => $block->getIdentifier(), 'label' => $block->getTitle()];
}
return $arrResult;
}
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange