3

The customer attribute shows up but cannot save it because there are no records about this attribute in eav_entity_attribute table, when I manually add a row for the attribute, it can be saved. How to deal with it? What was missed? Thanks.

namespace Namespace\ModuleName\Setup;

use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetup;
use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Setup\CustomerSetupFactory;

class UpgradeData implements UpgradeDataInterface {

    /**
     * Customer setup factory
     *
     * @var \Magento\Customer\Setup\CustomerSetupFactory
     */
    private $customerSetupFactory;

    /**
     * Init
     *
     * @param \Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory
     */
    public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory) {
        $this->customerSetupFactory = $customerSetupFactory;
    }


    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {

        $setup->startSetup();

        /** @var CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $customerSetup->addAttribute(
                Customer::ENTITY, 'abc', [
            'label' => 'ABC',
            'input' => 'select',
            'type' => 'int',
            'default' => false,
            'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
            'user_defined' => true,
            'required' => true,
            'position' => 82,
            'sort_order' => 82,
            'visible' => true,
            'system' => false,
            'is_used_in_grid' => true,
            'is_visible_in_grid' => true,
            'is_filterable_in_grid' => true,
            'is_searchable_in_grid' => true,
                ]
        );

        $customerSetup->updateAttribute('customer', 'myhkt', 'is_used_for_customer_segment', '1');

        // add attribute to form
        /** @var  $attribute */

        $attribute = $customerSetup->getEavConfig()->getAttribute('customer', 'abc');
        $attribute->setData('used_in_forms', ['adminhtml_customer']);
        $attribute->save();
        $setup->endSetup();
    }

}
9

I found the answer finally. adding:

   $attributeMyhkt->addData([
                'attribute_set_id' => 1,
                'attribute_group_id' => 1
            ]);

below:

 $attribute->setData('used_in_forms', ['adminhtml_customer']);

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.