- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-27-2024
06:09 AM
06-27-2024
06:09 AM
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
Pls help me...
Labels:
2 REPLIES 2
- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-27-2024
07:14 AM
06-27-2024
07:14 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-24-2024
09:53 PM
07-24-2024
09:53 PM
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"