While developing extensions in Magento 2 or to custom develop some requirements, you may sometimes need to get the list of all CMS pages in admin configuration of which one can select and use. Default Magento doesn’t provide such facility and thus I have come with the tutorial to help you out with this.
Let’s get started with the code to get CMS page list in System –> Configuration:
First of all, go to app -> code -> vendor -> module -> etc -> adminhtml -> system.xml and put below code in the file.
1 2 3 4 5 |
<field id="cmspage" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Select CMS Page</label> <source_model>{{VendorName}}\{{module name}}\Model\Config\Source\Cms</source_model> </field> |
Now put the below code in file app -> code -> vendor -> module -> model -> config -> source -> cms.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
namespace {{vemdor}}\{{module}}\Model\Config\Source; class Cms implements \Magento\Framework\Option\ArrayInterface { public function toOptionArray() { /** * @return array */ $res = array(); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $collection = $objectManager->get('\Magento\Cms\Model\ResourceModel\Page\CollectionFactory')->create(); $collection->addFieldToFilter('is_active' , \Magento\Cms\Model\Page::STATUS_ENABLED); foreach($collection as $page){ $data['value'] = $page->getData('identifier'); $data['label'] = $page->getData('title'); $res[] = $data; } return $res; } } |
Hope this tutorial has helped you implementing in many extensions or to fulfill your custom requirement of CMS page selection. Let me know if you have any doubt or issues regarding, I’ll be happy to assist you any time.