4

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;
      }
}
1
  • Did you solve it? I am stuck at exactly the same problem ...
    – hallleron
    Commented Jul 27, 2018 at 9:47

2 Answers 2

2

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();
   }
}
0
2

You can create custom customer attributes as below:

/public_html/development/app/code/Barcode/Unique/Setup/InstallData.php

namespace Barcode\Unique\Setup;
use Magento\Framework\Module\Setup\Migration; // It can be skipped
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface {

private $customerSetupFactory;

public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory) {
     $this->customerSetupFactory = $customerSetupFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
        $installer = $setup;
        $installer->startSetup();
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
    $entityTypeId = $customerSetup->getEntityTypeId(\Magento\Customer\Model\Customer::ENTITY);

    $customerSetup->removeAttribute(\Magento\Customer\Model\Customer::ENTITY, "barcode_unique");
        $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, "barcode_unique",  array(
        "type"     => "varchar",
        "backend"  => "",
        "label"    => "Barcode",
        "input"    => "text",
        "source"   => "",
        "visible"  => true,
        "required" => false,
        "default" => "",
        "frontend" => "",
        "unique"     => false,
        "note"       => ""

    ));
        $barcode_unique   = $customerSetup->getAttribute(\Magento\Customer\Model\Customer::ENTITY, "barcode_unique");

    $barcode_unique = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'barcode_unique');
      $used_in_forms[]="adminhtml_customer";
    $used_in_forms[]="checkout_register";
    $used_in_forms[]="customer_account_create";
    $used_in_forms[]="customer_account_edit";
    $used_in_forms[]="adminhtml_checkout";
        $barcode_unique->setData("used_in_forms", $used_in_forms)
        ->setData("is_used_for_customer_segment", true)
        ->setData("is_system", 0)
        ->setData("is_user_defined", 1)
        ->setData("is_visible", 1)
        ->setData("sort_order", 1002);
$barcode_unique->save();
$installer->endSetup();
}
}

You will have to create module and call this field in phtml file like:

/public_html/development/app/code/Barcode/Unique/view/frontend/templates/additionalinfocustomer.phtml

4
  • still got the same error
    – Hunter
    Commented Jun 21, 2017 at 1:57
  • Did you create the module? and you need clean,flush.upgrade and compile. I hope you did? and which version you are using? I just tested above code and its working fine(Magento 2.1.3). Above code is displaying field in admin and front. Clean cache manually from pub/static and other cached folders and deploy.
    – Jarnail S
    Commented Jun 21, 2017 at 3:44
  • yes it will work if i clean,flush.upgrade and compile, the problem is i'm running this function in controller not in InstallData, i cant run clean,flush.upgrade and compile everytime i call the controller to run this function
    – Hunter
    Commented Jun 21, 2017 at 3:54
  • According to magento doc, we should create new fields with installData and I havent try it with controller.
    – Jarnail S
    Commented Jun 21, 2017 at 3:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.