Skip to content

Instantly share code, notes, and snippets.

@sashas777
Last active February 5, 2017 02:23
Show Gist options
  • Save sashas777/3d1798a9d408a0c3083e8e412497ddcf to your computer and use it in GitHub Desktop.
Save sashas777/3d1798a9d408a0c3083e8e412497ddcf to your computer and use it in GitHub Desktop.
Magento 2.1.3 Make Customer Attribute - InstallData.php
<?php
/**
* @author Sashas IT Support <[email protected]>
* @copyright 2017 Sashas IT Support Inc. (http://www.extensions.sashas.org)
* @license http://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3 (GPL-3.0)
*/
namespace Sashas\CustomerAttribute\Setup;
use Magento\Customer\Setup\CustomerSetupFactory;
use Magento\Customer\Model\Customer;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
/**
* @codeCoverageIgnore
*/
class InstallData implements InstallDataInterface
{
/**
* Customer setup factory
*
* @var CustomerSetupFactory
*/
private $customerSetupFactory;
/**
* @var AttributeSetFactory
*/
private $attributeSetFactory;
/**
* Init
*
* @param CustomerSetupFactory $customerSetupFactory
*/
public function __construct(
CustomerSetupFactory $customerSetupFactory,
AttributeSetFactory $attributeSetFactory
) {
$this->customerSetupFactory = $customerSetupFactory;
$this->attributeSetFactory = $attributeSetFactory;
}
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
/** @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$setup->startSetup();
$attributesInfo = [
'magento_username' => [
'label' => 'Magento Username',
'type' => 'varchar',
'input' => 'text',
'position' => 1000,
'visible' => true,
'required' => false,
'system' => 0,
'user_defined' => true,
'position' => 1000,
]
];
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
/** @var $attributeSet AttributeSet */
$attributeSet = $this->attributeSetFactory->create();
$attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);
foreach ($attributesInfo as $attributeCode => $attributeParams) {
$customerSetup->addAttribute(Customer::ENTITY, $attributeCode, $attributeParams);
}
$magentoUsernameAttribute = $customerSetup->getEavConfig()->getAttribute(Customer::ENTITY, 'magento_username');
$magentoUsernameAttribute->addData([
'attribute_set_id' => $attributeSetId,
'attribute_group_id' => $attributeGroupId,
'used_in_forms' => ['adminhtml_customer'],
]);
$magentoUsernameAttribute->save();
$setup->endSetup();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment