photo credit: Done and not done via photopin (license)

Magento 2 : Use custom source models for multiselect product attributes


Source models in Magento 2 are very simple. They simply are classes that return a list of properties. A very basic example:

You can use this source model in configuration files or in the source_model-column of your EAV attribute.
But …
When you want to use multiselect instead of select, you might encounter the following error:

What’s happening here, and more importantly: how can we fix this?


It’s all in the configuration of your model. If you’ve created a multiselect attribute in the admin, it’s backend model is set to Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend . As you can see, this is an EAV model. For this reason, the source model, must also take EAV into account. How can we do this? Simple: just extend your source model from Attribute\Source\AbstractSource  and implement the getAllOptions() -method (which returns the same 2-dimensional array with value and label-keys):

That’s it! The error will be gone and you’ll be able to use your custom source model for multiselect product attributes in Magento 2!

Visitors give this article an average rating of 3.7 out of 5.

How would you rate this article?

Leave a Reply