1

How to create product attributes in Magento 2 so it works in running script without install script

  • using custom script ? – Rk Rathod Aug 13 at 7:13
  • My requirement is need to check before create product that attribute exist or not. If not then it should create first. – Parth Aug 13 at 10:08
1

Write down an observer catalog_product_save_before and check the attribute existence on this observer.

etc/adminhtml/events.xml

<event name="catalog_product_save_before">
    <observer name="check_existing_attribute" instance="FirstVendor\FirstModule\Observer\CheckAttributeBeforeObserver"/>
</event>

observer/CheckAttributeBeforeObserver.php

<?php
namespace FirstVendor\FirstModule\Observer;

use Magento\Catalog\Model\Product;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Eav\Api\AttributeRepositoryInterface;

class CheckAttributeBeforeObserver implements ObserverInterface
{

    private $eav;


    public function __construct(
        AttributeRepositoryInterface $AttributeRepositoryInterface
    ) {
        $this->eav = $AttributeRepositoryInterface;
    }

    /**
     * check attribute existance
     *
     * @param EventObserver $observer
     * @return boolean
     */
    public function execute(EventObserver $observer)
    {
        $product = $observer->getEvent()->getProduct();
        $attribute = $this->eav->get("catalog_product", "name");
        if(!empty($attribute->getAttributeCode())){
            return false;
        }
        return true;
    }
}
  • Command to execute this would be like: php bin/magento create_attribute testattribute – Rahul Anand Aug 13 at 9:40
  • Thanks Rahul, this seems created on command call. but my requirement is need to check before create product that attribute exist or not. If not then it should create first. – Parth Aug 13 at 10:08
  • Oh gotcha. Write down an event before product save and use eavfactory to check attribute exist or not. I will write it down and send your the code. – Rahul Anand Aug 13 at 10:12
  • That's great, thank you. – Parth Aug 14 at 5:36
  • Hi parth, I have updated my comment with the updated code for an event. Please check it. – Rahul Anand Aug 14 at 7:13
0

Created a helper class (ProductAttribute.php) to check attribute exist or not, If not exist then it will create attribute.

<?php
namespace Vendor\Module\Helper;

use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;

class ProductAttribute extends \Magento\Framework\App\Helper\AbstractHelper {

    /**
     * @var \Magento\Eav\Setup\EavSetupFactory
     */
    protected $eavEavSetupFactory;
    protected $eavConfig;
    protected $attributeSetFactory;

    public function __construct(
        \Magento\Eav\Setup\EavSetupFactory $eavEavSetupFactory,
        \Magento\Eav\Model\Config $eavConfig,       
        AttributeSetFactory $attributeSetFactory
    ) {
        $this->eavEavSetupFactory = $eavEavSetupFactory;
        $this->attributeSetFactory = $attributeSetFactory;
        $this->eavConfig = $eavConfig;
    }

    public function createOrUpdateProductUDA($value, $input, $type) {

        $attributeCode = $this->getAttributeCode($value);

        // Check Attribute already exist or not
        $attribute = $this->eavConfig->getAttribute('catalog_product', $attributeCode);
        if (!$attribute || !$attribute->getAttributeId()) {
            throw new NoSuchEntityException(
                __('Attribute with attributeCode "%1" does not exist.', $attributeCode)
            );

            return true;
        }

        /** @var ProductSetup $productSetup */
        $productSetup = $this->eavEavSetupFactory->create();

        $productEntity = $productSetup->getEntityTypeId('catalog_product');
        $attributeSetId = $productSetup->getDefaultAttributeSetId($productEntity);

        /** @var $attributeSet AttributeSet */
        $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        // print_r(get_class_methods($productSetup));
        $productSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            $value,
            [
                'type' => $type,
                'backend' => '',
                'frontend' => '',
                'label' => $attributeCode,
                'input' => $input,
                'class' => '',
                'source' => '',
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_GLOBAL,
                'visible' => true,
                'required' => false,
                'user_defined' => false,
                'default' => '',
                'searchable' => false,
                'filterable' => false,
                'comparable' => false,
                'visible_on_front' => true,
                'used_in_product_listing' => true,
                'unique' => false,
                'apply_to' => ''
            ]
        );

        return true;
    }

    protected function getAttributeCode($str)   {
        return strtolower(str_replace(" ", "", $str));    
    } 
}

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.