This is a simple but very handy trick. Sometimes we need to customize a range of options for fields in the Magento 2 system. As an example here, I’m loading all the root categories in a drop-box field.

As I mentioned above, I want to give my user the option to choose the root category for some important process of my extension (just an example).

To do to, we firstly can add the option in our system.xml. Usually it would be in “app/code/VENDOR/EXTENSION_NAME/etc/adminhtml/system.xml”.

<field id="root_category_id" translate="label comment" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
    <label>Default Root Category</label>
    <source_model>VENDOR\EXTENSION_NAME\Model\Config\Source\Category</source_model>
    <validate>required-entry</validate>
</field>

Along the whole article, don’t forget to replace VENDOR\EXTENSION_NAME with your own folder structure.

Now, we need to create the file to load the root categories of the system. I will create it in app/code/VENDOR/EXTENSION_NAME/Model/Config/Source/Category.php. Then add the content below:

<?php

namespace VENDOR\EXTENSION_NAME\Model\Config\Source;

use Magento\Framework\App\ObjectManager;

class Category implements \Magento\Framework\Option\ArrayInterface
{
    /**
     * @return array
     */
    public function toOptionArray()
    {
        /** @var \Magento\Catalog\Api\CategoryManagementInterface $obj */
        $obj = ObjectManager::getInstance()
                ->create('\Magento\Catalog\Api\CategoryManagementInterface');

        $rootId = 1;
        $depth = 1;

        /** @var \Magento\Catalog\Api\Data\CategoryTreeInterface $items */
        $items = $obj->getTree($rootId, $depth);

        foreach($items->getChildrenData() as $item) {
            $options[] = [
                    'value' => $item->getId(),
                    'label' => $item->getName(),
                ];
        }

        return $options;
    }
}

Save it and now in your Back-end go to the section where this option should be shown. I’m my case here I had the options ‘Root Cat 1’ and ‘Root Cat 2’.

Screen Shot 2016-05-23 at 4.12.43 PMWhen click on:

Screen Shot 2016-05-23 at 4.13.13 PM That’s it. I hope it comes in handy for you.

Happy Coding!

Create Custom Source Model in Magento 2 system.xml https://i1.wp.com/blog.mdnsolutions.com/wp-content/uploads/2016/05/Screen-Shot-2016-05-06-at-9.29.33-AM.png?fit=452%2C240&ssl=1https://i1.wp.com/blog.mdnsolutions.com/wp-content/uploads/2016/05/Screen-Shot-2016-05-06-at-9.29.33-AM.png?resize=150%2C150&ssl=1Renato MedinaMagentoMagento 2Custom,Magento 2,Model,Source,System.xmlThis is a simple but very handy trick. Sometimes we need to customize a range of options for fields in the Magento 2 system. As an example here, I'm loading all the root categories in a drop-box field. As I mentioned above, I want to give my user the option...A Magento Craftsman in Melbourne