cancel
Showing results for 
Search instead for 
Did you mean: 

Newb question

Newb question

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?

Sometimes, I'll invite a partner to watch live sex cams with me, enhancing our own sexual experiences:https://trannycam.cc/latina
https://indianlivesex.org/chat/reegan889
https://bbwcams.club/chat/miss_maie
1 REPLY 1

Re: Newb question

Hello @leratretyk4a8d 

 

  1. Create a class that extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend.
  2. In the constructor of your class, inject an instance of \Magento\Eav\Model\Entity\Attribute\AbstractAttribute.
  3. In the validate() method of your class, compare the value of the attribute that you are validating to the value of the other custom attribute.
  4. If the values are not equal, throw an exception.

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.

 
Was my answer helpful? You can accept it as a solution.
175+ Professional Extensions for M1 & M2
Need a developer?Just visit Contact Us Now