質問

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')]];
   }
}
役に立ちましたか?

解決

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!

ライセンス: CC-BY-SA帰属
所属していません magento.stackexchange
scroll top