My module adds a custom dropdown attribute to categories. This attribute has many possible values, but in most cases (~90%) users will leave the default value in the attribute's field.

I want to make sure the attribute will not be saved in the database for categories in which user selected the default value. This will save some space in the database and (I hope) it will increase performance a little bit.

So I created a backend model for my attribute and in the beforeSave method I check the value of the attribute before it is finally saved in the database. If the current value is the default value, I replace it with an empty string ''. See an example:

class ProductType extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
    const DEFAULT_VALUE = 'smartphones';

    public function beforeSave($object)
        $attrCode = $this->getAttribute()->getAttributeCode();
        $attrValue = $object->getData($attrCode);

        // If default value, don't save that attribute
        if ($attrValue === self::DEFAULT_VALUE) {
            $object->setData($attrCode, '');

Is it the correct way to prevent saving the attribute in the database?

Or should I replace the value of the attribute with null instead of an empty string ''? Like this:

        if ($attrValue === self::DEFAULT_VALUE) {
            $object->setData($attrCode, null);

I'm not sure this will improve performance but to me you should use the unsetter instead of setting the value to an empty string or null:


This will definitely avoid any value being saved to the database for this particular attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.