I need to create customer custom attribute.
In module.xml
<sequence>
<module name="Magento_Customer"/>
</sequence>
in upgrade schema UpgradeSchema.php
namespace Namespace\Modulename\Setup;
use Magento\Customer\Model\Customer;
use Magento\Customer\Setup\CustomerSetup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class UpgradeSchema implements UpgradeSchemaInterface
{
private $customerSetupFactory;
public function __construct(\Magento\Customer\Setup\CustomerSetupFactory $customerSetupFactory)
{
$this->customerSetupFactory = $customerSetupFactory;
}
public function upgrade(SchemaSetupInterface $setup,
ModuleContextInterface $context){
$setup->startSetup();
if (version_compare($context->getVersion(), '0.0.4') < 0) {
/** @var CustomerSetup $customerSetup */
$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
$customerSetup->addAttribute(
Customer::ENTITY,
'example1',
[
'label' => 'Example Attribute',
'required' => 0,
'system' => 0, // <-- important, otherwise values aren't saved.
// @see Magento\Customer\Model\Metadata\CustomerMetadata::getCustomAttributesMetadata()
'position' => 100
]
);
$customerSetup->getEavConfig()->getAttribute('customer', 'example1')
->setData('used_in_forms', ['adminhtml_customer'])
->save();
}
$setup->endSetup();
}
}
I am getting error
Recoverable Error: Argument 1 passed to
Magento\Customer\Setup\CustomerSetu p::__construct() must implement
interface Magento\Framework\Setup\ModuleDat aSetupInterface,
instance of Magento\Setup\Module\Setup given, called in /vendor/magento/framework/ObjectManager/Factory/Abstrac
tFactory.php on line 93 and defined in
/vendor/magento
o/module-customer/Setup/CustomerSetup.php
Best Answer
You could not create a customer attribute using magento schema files both
InstallSchema
and UpgradeSchema.Need to use data files InstallData and UpgradeData.Because of in order create an attribute you should inject
Magento\Customer\Setup\CustomerSetupFactory
on__construct function of your class
andMagento\Customer\Setup\CustomerSetup
main class of this factory class.But this class
Magento\Customer\Setup\CustomerSetup
class injects atMagento\Framework\Setup\ModuleDataSetupInterface
on it's __construct function.And as you use
Magento\Framework\Setup\InstallSchemaInterface
andMagento\Framework\Setup\SchemaSetupInterface
.So it cannot be possible to get interface
Magento\Framework\Setup\ModuleDataSetupInterface
atMagento\Customer\Setup\CustomerSetup
.And you can only use
Magento\Framework\Setup\ModuleDataSetupInterface
on data installdata and upgradedata file mean data installer file.Solution is that you should use UpgradeData.php instead of UpgradeSchema.php
Installer should be