Magento2 – Fix Attribute with Same Code Already Exists Error

controllerscustomer-attributemagento2

i try following this tutorial to add new customer attribute, the tutorial run the function at InstallData.php. I'm trying to run the function from controller and i got the following error:

"Attribute with the same code already exists.";i:1;s:6637:"#0 /var/www/project/vendor/magento/framework/Model/ResourceModel/Db/AbstractDb.php(400)

here's my controller code:

    use Magento\Framework\App\Filesystem\DirectoryList;

    use Magento\Eav\Setup\EavSetup;
    use Magento\Eav\Setup\EavSetupFactory;
    use Magento\Eav\Model\Config;
    use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
    use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
    use Magento\Framework\Setup\ModuleDataSetupInterface;
    use Magento\Customer\Setup\CustomerSetupFactory;
    use Magento\Customer\Model\Customer;

    class Save extends \Magento\Backend\App\Action
    {
      protected $idListing;

      public function __construct(
            CustomerSetupFactory $customerSetupFactory,
            AttributeSetFactory $attributeSetFactory,
            ModuleDataSetupInterface $setup,
            ModuleContextInterface $contextt,
            \Magento\Backend\App\Action\Context $context
        ) {
            $this->customerSetupFactory = $customerSetupFactory;
            $this->attributeSetFactory = $attributeSetFactory; 
            $this->setup =$setup;
            parent::__construct($context);
        }

      private function saveAttribute(){
        $context = $this->contextt;
        $setup = $this->setup; 
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

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

        $customerSetup->addAttribute(Customer::ENTITY, 'test1234', [
            'type' => 'varchar',
            'label' => 'test',
            'input' => 'text',
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 1000,
            'position' => 1000,
            'system' => 0,
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'test1234')
        ->addData([
            'attribute_set_id' => $attributeSetId,
            'attribute_group_id' => $attributeGroupId,
            'used_in_forms' => ['adminhtml_customer'],
        ]);
        try {
          $attribute->save();
          echo "success";
        } catch (Exception $e) {
          print_r($e->getMessage());
        }
        exit;
      }

      public function execute()
      {

         $this->saveAttribute();
         exit;
      }
}

Best Answer

Before you run the function to save to eav attribute, you can try clean magento cache programmatically like this:

public function __construct( 
   \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList,
   \Magento\Framework\App\Cache\Frontend\Pool $cacheFrontendPool
) { 
   $this->_cacheTypeList = $cacheTypeList;
   $this->_cacheFrontendPool = $cacheFrontendPool; 
}

private function cleanCache(){
   $types = array('config','layout','block_html','collections','reflection','db_ddl','eav','config_integration','config_integration_api','full_page','translate','config_webservice');
   foreach ($types as $type) {
     $this->_cacheTypeList->cleanType($type);
   }
   foreach ($this->_cacheFrontendPool as $cacheFrontend) {
     $cacheFrontend->getBackend()->clean();
   }
}
Related Topic