Skip to main content

Custom Attributes in System Configuration in Magento 2

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Philipp Sander

In one of our current Magento 2 projects we have the need to create a custom shipping method which that should not be selectable when there a product in our cart with a specific value selected in a custom attribute.

In order to make it flexible which values should disable the shipping method we created a configuration for the shipping method. This way you can change the values in the admin backend without the need to change and redeploy the code. The problem was that you can't simply use the model in the <source> tag of the configuration, but the solution we came up with was quite simple and generic:

We created a class that provides all options of the custom attribute. In our case, the custom attribute was called 'series'.


namespace \bitExpert\CustomModule\Model\Config\Source\SeriesOptions;

use Magento\Catalog\Model\Product\Attribute\Repository;
use \Magento\Framework\Data\OptionSourceInterface;

class SeriesOptions implements OptionSourceInterface
* @var AttributeRepositoryInterface
private $attributeRepository;

* SeriesOptions constructor.
* @param AttributeRepository $attributeRepository
public function __construct(AttributeRepository $attributeRepository) {
$this->attributeRepository = $attributeRepository;

* Returns an array of all options of the series attribute
* @return array|null
public function toOptionArray()
/** @var \Magento\Eav\Model\Attribute $attribute */
$attribute = $this->attributeRepository->get('series');
$options = $attribute->getOptions();

return $options;

Then you can simply use this class in the system configuration - system.xml

<field id="excluded_series" translate="label" type="multiselect" 
sortOrder="0" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Series that will make shipping method unavailable</label>

Now you can easily retrieve the selected values with the ScopeConfig.