Hello,
I'm new to Magento and I'm creating a module that adds two attributes to products via a Setup/InstallData class and using EavSetupFactory.
This is working fine and I've got a class passed via the 'backend' key in the array passed to addAttribute() to handle validation. That's also working OK, I can check the submitted value of the attribute and throw an exception if it fails validation.
The problem is I can't see how I can compare it to the other custom attribute, I can only write code that validates one attribute at a time. I've looked at attribute sets and groups but they don't seem to be the right thing.
Can anyone point me in the right direction?
Hello @leratretyk4a8d
Here is an example of how you could implement this solution:
<?php
namespace Vendor\Module\Model\Entity\Attribute\Backend;
use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend;
use Magento\Eav\Model\Entity\Attribute\AbstractAttribute;
class CompareBackend extends AbstractBackend
{
    protected $otherAttribute;
    public function __construct(
        AbstractAttribute $attribute,
        \Magento\Eav\Model\Entity\Attribute\AbstractAttribute $otherAttribute
    ) {
        parent::__construct($attribute);
        $this->otherAttribute = $otherAttribute;
    }
    public function validate($object)
    {
        $value1 = $this->getAttribute()->getValue($object);
        $value2 = $this->otherAttribute->getValue($object);
        if ($value1 !== $value2) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('The values of the two attributes must be equal.')
            );
        }
    }
}Once you have created this class, you can use it to validate the values of two custom attributes in Magento 2.