cancel
Showing results for 
Search instead for 
Did you mean: 

Create custom attribute

Create custom attribute

Hi all. I have a problem with my code for create atrribute:

$attribute = $this->attributeFactory->create();

$attribute->setAttributeCode($data['code']);
$attribute->setEntityTypeId($data['entity_type_id']);
$attribute->setFrontendInput($data['input_type']);
$attribute->setDefaultFrontendLabel($data['label']);
$attribute->setIsUserDefined($data['is_user_defined']);
$attribute->setIsRequired($data['is_required']);
$attribute->setBackendType('varchar');

$this->attributeRepository->save($attribute);

Magento\Eav\Model\Entity\AttributeFactory and Magento\Eav\Model\Entity\Attribute\SetFactory are undefined classes Smiley Sad

 

Pls help me...

 

2 REPLIES 2

Re: Create custom attribute

It looks like you're missing some dependencies for your code. You'll need to inject the

\Magento\Eav\Model\Entity\AttributeFactory

and potentially

\Magento\Eav\Model\Entity\Attribute\SetFactory

using dependency injection.

Re: Create custom attribute

It looks like you're trying to create an EAV attribute in Magento 2. The error about undefined classes suggests that the classes

Magento\Eav\Model\Entity\AttributeFactory and Magento\Eav\Model\Entity\Attribute\SetFactory are not being correctly injected.

You have to declare them.

below is the basic code of how You can use it to create the attribute.

<?php
use Magento\Eav\Api\AttributeRepositoryInterface;
use Magento\Eav\Model\Entity\AttributeFactory;
use Magento\Framework\App\ResourceConnection;

class YourClass
{
    protected $attributeRepository;
    protected $attributeFactory;
    protected $resourceConnection;
    public function __construct(

        AttributeRepositoryInterface $attributeRepository,
        AttributeFactory $attributeFactory,
        ResourceConnection $resourceConnection

    ) {
        $this->attributeRepository = $attributeRepository;
        $this->attributeFactory = $attributeFactory;
        $this->resourceConnection = $resourceConnection;
      }

    public function createAttribute(array $data)
    {
        $attribute = $this->attributeFactory->create();
        $attribute->setAttributeCode($data['code']);
        $attribute->setEntityTypeId($data['entity_type_id']);
        $attribute->setFrontendInput($data['input_type']);
        $attribute->setDefaultFrontendLabel($data['label']);
        $attribute->setIsUserDefined($data['is_user_defined']);
        $attribute->setIsRequired($data['is_required']);
        $attribute->setBackendType('varchar');
        $this->attributeRepository->save($attribute);
    }
}

If you've found my answer useful, please give "Kudos" and "Accept as Solution"