In this article we will explore how to create a customer EAV attribute and how to control where is available in the store. In Commerce version store admins are able to add the attributes same as for other EAV types. For community version this feature is not available. Not to worry it very easy to add a customer attribute programmatically.
Before we start you can visit the official guide here. Keep in mind that the official guide mentions the following:
Both the save() and getResource() methods for Magento\Framework\Model\AbstractModel have been marked as @deprecated since 2.1 and should no longer be used.
However they do not provide an alternative for how to process the attributes. We will handle this part as well.
First thing you will need is an active module. We assume you are familiar on how to create one. Once you have that we will need to create a data patch script. If you are interested on more details about data patches you can visit another example here.\
Our data patches will reside in the following directory:
Techflarestudio\Attributes\Setup\Patch\Data
Our vendor and module name is Techflarestudio\Attributes
The patch files will reside in Setup\Patch\Data
Lets create our data patch class, we will call it AddCustomerCertificationAttribute.
Couple of things to break down here:
The customerSetupFactory class allows us to instantiate a setup class
We are using addAttribute function to create a boolean type attribute, add sanitize backend class which cleans up the values, making sure the attribute is set as system false which will allow us to edit this in other forms.
We will use Magento\Customer\Model\ResourceModel\Attribute to update the used_in_forms. Since the
We are using all available forms but you should keep this to minimum required. If you ever need you can create another data patch to update the available forms.