I have used the following script to add a custom customer attribute.
<?php
namespace Harrigo\ContractPricing\Setup;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface {
protected $customerSetupFactory;
private $attributeSetFactory;
public function __construct(CustomerSetupFactory $customerSetupFactory, AttributeSetFactory $attributeSetFactory) {
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
$customerSetup->addAttribute(Customer::ENTITY, 'cp_permissions', [
'type' => 'static',
'label' => 'Account Type',
'input' => 'select',
'source' => \Magento\Eav\Model\Entity\Attribute\Source\Table::class,
'required' => false,
'visible' => true,
'user_defined' => false,
'sort_order' => 101,
'position' => 101,
'system' => false,
'adminhtml_only' => true,
'option' => ['values' => ['Master', 'Branch']]
]);
$attribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'cp_permissions')
->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer'],
]);
$attribute->save();
}
}
The attribute after some difficulty now shows on the form however no longer saved. Initially the attribute didn't show until i set the source
differently and set user_defined to false. I originally changed these in database and all worked however now that i've got the installer script almost working (attribute shows and source was set within database) i have noticed that values are not saving.
I have checked and system
value is set to 0 / false in customer_eav_attribute
table.
Best Answer
Change attribute
type
tovarchar
instead ofstatic
, and try again.Add Attribute: