Skip to content

2.4.6: Filter available attribute sets according to product type, using a plugin

In my custom plugin, the InstallData.php script creates a custom attribute set. For the purposes of this Q&A, we will call it ‘Custom Attribute Set #1’.

I would like the attribute set to only be applicable to products of type ‘simple’.

In order to achieve this, I have implemented the following plugin:

<?php
namespace MyOrganisationMyModulePlugin;

use MagentoCatalogModelProductAttributeSetOptions as AttributeSetOptions;
use MagentoFrameworkAppRequestInterface;

class AttributeSetOptionsPlugin
{
    /**
     * @var RequestInterface $request
     */
    private RequestInterface $request;

    public function __construct(
        RequestInterface $request
    ) {
        $this->request = $request;
    }

    public function afterToOptionArray(
        AttributeSetOptions $subject,
        $result
    ) {

        // If the user is attempting to create a new product
        if($this->request->getActionName() === 'new') {

            // If the product type is not 'simple'.
            if($this->request->getParam('type') !== 'simple') {

                $result = array_filter($result, function($attributeSet) {

                    // Exclude all attribute sets with the label 'Custom Attribute Set #1'.
                    // TODO: Later we should compare against a centralised list of attribute set labels, to ensure coherence across the application as well as offer greater extensibility.
                    if($attributeSet['label'] === 'Custom Attribute Set #1') {
                        return false;
                    }

                    return true;

                });
            }
        }

        return $result;
    }
}

If I inject the logger and test the returned value of $result, it is correct – where the product type does not equal ‘simple’, the custom attribute set is removed from the $result array.

However, the change is not reflected in the admin panel and, when I attempt to create a new product of any type, ‘Custom Attribute Set #1’ remains visible in the dropdown list.

Not sure if I should be creating a custom view in order to consume an alternative data source, or if the plugin should be triggered in a different location (earlier, perhaps), or something else.