Create source for custom attribute (Magento 2)

To create source for custom attribute in Magento 2 follow the steps:

Step1: Create a module in Company\Module\Model\Source folder and add the following code:

<?php
namespace Company\Module\Model\Source;

use Psr\Log\LoggerInterface;
/**
 * Class AttributeOptionList 
 */
class AttributeOptionList extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{

    /**
     * @var LoggerInterface $logger
     */
    protected $logger;

    public function __construct(
        \Magento\Eav\Model\Config $eavConfig,
        LoggerInterface $logger
    ) {
        $this->_eavConfig = $eavConfig;
        $this->logger = $logger;
    }

    public function getAllOptions() {
       $attributeCode = "attribute_code";
        $attribute = $this->_eavConfig->getAttribute('catalog_product', $attributeCode);
        $options = $attribute->getSource()->getAllOptions();
        $arr = [];
        foreach ($options as $option) {
            if ($option['value'] > 0) {
                $arr[] = $option;
            }
        }
        $this->logger->info('++++++++++++++ attribute options++++++++++' . print_r($arr,true));  
        return $arr;
    }
}

Step2: Class created in first step will use to create system configuration in admin side. To do this:

  1. Create system.xml file in etc/adminhtml
  2. Add following code:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
<section id="attributename" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1"
                 showInStore="1">
            <label>Label for Admin</label>
            <tab>Tab Name</tab>
            <resource>Company_Module::config</resource>
            <group id="unique_groupid" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1"
                   showInStore="1">
                <label>Group label</label>
             <field id="unique_field_id" translate="label" type="multiselect" sortOrder="20" showInDefault="1" showInWebsite="1"
                       showInStore="1">
                    <label>Field Label</label>
                    <source_model>Company\Module\Model\Source\AttributeOptionList</source_model>
                </field>
             </group>
</section>
    </system>
</config>

This will create multiselect option for all options custom attribute have.

Create source for custom attribute

Reference: https://devdocs.magento.com/