Como adicionar um campo personalizado no cadastro do cliente (admin) – Magento 2

Post ensinando a como adicionar um campo personalizado no cadastro do cliente (disponivel apenas para o Admin) no Magento 2.

campo personalizado no Magento 2

O campo personalizado de exemplo que iremos adicionar é o corporate_id, tipo String “TYPE_TEXT”.

Todos os arquivos no vendor files

customer_form.xml

<field name="corporate_id">
 <argument name="data" xsi:type="array">
 <item name="config" xsi:type="array">
 <item name="label" xsi:type="string" translate="true">Corporate ID</item>
 <item name="dataType" xsi:type="string">text</item>
 <item name="formElement" xsi:type="string">input</item>
 <item name="source" xsi:type="string">customer</item>
 </item>
 </argument>
...

customer_list.xml

...
<column name="corporate_id">
 <argument name="data" xsi:type="array">
 <item name="config" xsi:type="array">
 <item name="filter" xsi:type="string">text</item>
 <item name="label" xsi:type="string" translate="true">Corporate ID</item>
 <item name="sortOrder" xsi:type="number">30</item>
 </item>
 </argument>
</column>

installSchema.xml

/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magento\Customer\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

/**
 * @codeCoverageIgnore
 */
class InstallSchema implements InstallSchemaInterface
{
    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();

        /**
         * Create table 'customer_entity'
         */
        $table = $installer->getConnection()->newTable(
            $installer->getTable('customer_entity')
        )->addColumn(
            'entity_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
            'Entity Id'
        )->addColumn(
            'website_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['unsigned' => true],
            'Website Id'
        )->addColumn(
            'email',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [],
            'Email'
         )->addColumn(
            'corporate_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            [],
            'Corporate Id'
        )->addColumn(
            'group_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['unsigned' => true, 'nullable' => false, 'default' => '0'],
            'Group Id'
            ['unsigned' => true, 'nullable' => true, 'default' => null],
            'Default Billing Address'
       )->addIndex(
            $installer->getIdxName(
                'customer_entity',
                ['email', 'website_id'],
                \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
            ),
            ['email', 'website_id'],
            ['type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE]
        )->addIndex(
            $installer->getIdxName('customer_entity', ['website_id']),
            ['website_id']
        )->addIndex(
            $installer->getIdxName('customer_entity', ['firstname']),
            ['firstname']
        )->addIndex(
            $installer->getIdxName('customer_entity', ['corporate_id']),
            ['corporate_id']
        )->addIndex(
            $installer->getIdxName('customer_entity', ['lastname']),
            ['lastname']
        )->addForeignKey(
            $installer->getFkName('customer_entity', 'store_id', 'store', 'store_id'),
            'store_id',
            $installer->getTable('store'),
            'store_id',
            \Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
        )->addForeignKey(
            $installer->getFkName('customer_entity', 'website_id', 'store_website', 'website_id'),
            'website_id',
            $installer->getTable('store_website'),
            'website_id',
            \Magento\Framework\DB\Ddl\Table::ACTION_SET_NULL
        )->setComment(
            'Customer Entity'
        );
        $installer->getConnection()->createTable($table);

        /**
         * Create table 'customer_address_entity'
         */
     
        /**
         * Create table 'customer_eav_attribute_website'
         */
        $table = $installer->getConnection()->newTable(
            $installer->getTable('customer_eav_attribute_website')
        )->addColumn(
            'attribute_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['unsigned' => true, 'nullable' => false, 'primary' => true],
            'Attribute Id'
        )->addColumn(
            'website_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['unsigned' => true, 'nullable' => false, 'primary' => true],
            'Website Id'
        )->addColumn(
            'is_visible',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['unsigned' => true],
            'Is Visible'
        )->addColumn(
            'is_required',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['unsigned' => true],
            'Is Required'
        )->addColumn(
            'default_value',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            '64k',
            [],
            'Default Value'
        )->addColumn(
            'multiline_count',
            \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
            null,
            ['unsigned' => true],
            'Multiline Count'
        )->addIndex(
            $installer->getIdxName('customer_eav_attribute_website', ['website_id']),
            ['website_id']
        )->addForeignKey(
            $installer->getFkName('customer_eav_attribute_website', 'attribute_id', 'eav_attribute', 'attribute_id'),
            'attribute_id',
            $installer->getTable('eav_attribute'),
            'attribute_id',
            \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
        )->addForeignKey(
            $installer->getFkName('customer_eav_attribute_website', 'website_id', 'store_website', 'website_id'),
            'website_id',
            $installer->getTable('store_website'),
            'website_id',
            \Magento\Framework\DB\Ddl\Table::ACTION_CASCADE
        )->setComment(
            'Customer Eav Attribute Website'
        );
        $installer->getConnection()->createTable($table);

        /**
         * Create table 'customer_visitor'
         */
        $table = $installer->getConnection()->newTable(
            $installer->getTable('customer_visitor')
        )->addColumn(
            'visitor_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_BIGINT,
            null,
            ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
            'Visitor ID'
        )->addColumn(
            'customer_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
            null,
            [],
            'Customer Id'
        )->addColumn(
            'session_id',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            64,
            ['nullable' => true, 'default' => null],
            'Session ID'
        )->addColumn(
            'last_visit_at',
            \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
            null,
            ['nullable' => false],
            'Last Visit Time'
        )->addIndex(
            $installer->getIdxName('customer_visitor', ['customer_id']),
            ['customer_id']
        )->setComment(
            'Visitor Table'
        );
        $installer->getConnection()->createTable($table);

        $table = $installer->getConnection()
            ->newTable(
                $installer->getTable('customer_log')
            )
            ->addColumn(
                'log_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                null,
                [
                    'nullable' => false,
                    'identity' => true,
                    'primary' => true
                ],
                'Log ID'
            )
            ->addColumn(
                'customer_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                null,
                [
                    'nullable' => false
                ],
                'Customer ID'
            )
            ->addColumn(
                'last_login_at',
                \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                null,
                [
                    'nullable' => true,
                    'default' => null
                ],
                'Last Login Time'
            )
            ->addColumn(
                'last_logout_at',
                \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                null,
                [
                    'nullable' => true,
                    'default' => null
                ],
                'Last Logout Time'
            )
            ->addIndex(
                $installer->getIdxName(
                    $installer->getTable('customer_log'),
                    ['customer_id'],
                    \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
                ),
                ['customer_id'],
                [
                    'type' => \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_UNIQUE
                ]
            )
            ->setComment('Customer Log Table');
        $installer->getConnection()->createTable($table);

        $installer->endSetup();

    }
}

customerSetup.xml

public function getDefaultEntities(){
	$entities = [
		'customer' => [
			'entity_type_id' => \Magento\Customer\Api\CustomerMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
			'entity_model' => 'Magento\Customer\Model\ResourceModel\Customer',
			'attribute_model' => 'Magento\Customer\Model\Attribute',
			'table' => 'customer_entity',
			'increment_model' => 'Magento\Eav\Model\Entity\Increment\NumericValue',
			'additional_attribute_table' => 'customer_eav_attribute',
			'entity_attribute_collection' => 'Magento\Customer\Model\ResourceModel\Attribute\Collection',
			'attributes' => [
				'website_id' => [
					'type' => 'static',
					'label' => 'Associate to Website',
					'input' => 'select',
					'source' => 'Magento\Customer\Model\Customer\Attribute\Source\Website',
					'backend' => 'Magento\Customer\Model\Customer\Attribute\Backend\Website',
					'sort_order' => 10,
					'position' => 10,
					'adminhtml_only' => 1,
				],
				'store_id' => [
					'type' => 'static',
					'label' => 'Create In',
					'input' => 'select',
					'source' => 'Magento\Customer\Model\Customer\Attribute\Source\Store',
					'backend' => 'Magento\Customer\Model\Customer\Attribute\Backend\Store',
					'sort_order' => 20,
					'visible' => false,
					'adminhtml_only' => 1,
				],
				'corporate_id' => [
					'type' => 'static',
					'input' => 'text',
					'backend' => 'Magento\Customer\Model\Customer\Attribute\Backend\Corporate',
					'required' => false,
					'sort_order' => 20,
					'visible' => false,
					'position' => 20,
					 'adminhtml_only' => 1,
				],]]
				...
}

indexer.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Indexer/etc/indexer.xsd">
    <indexer id="customer_grid" view_id="customer_dummy" class="Magento\Framework\Indexer\Action\Entity" primary="customer">
        <title translate="true">Customer Grid</title>
        <description translate="true">Rebuild Customer grid index</description>

        <fieldset name="customer" source="Magento\Customer\Model\ResourceModel\Customer\Collection"
                  provider="Magento\Customer\Model\Indexer\AttributeProvider">
            <field name="corporate_id" xsi:type="searchable" dataType="varchar"/>       
            <field name="name" xsi:type="searchable" dataType="text" handler="CustomerNameHandler"/>
            <field name="email" xsi:type="searchable" dataType="varchar"/>

            <field name="group_id" xsi:type="filterable" dataType="int"/>
            <field name="created_at" xsi:type="filterable" dataType="timestamp"/>
            <field name="website_id" xsi:type="filterable" dataType="int"/>
            <field name="confirmation" xsi:type="filterable" dataType="varchar"/>
            <field name="created_in" xsi:type="filterable" dataType="text"/>
            <field name="dob" xsi:type="filterable" dataType="date"/>
            <field name="gender" xsi:type="filterable" dataType="int"/>
            <field name="taxvat" xsi:type="searchable" dataType="varchar"/>
            <field name="lock_expires" xsi:type="filterable" dataType="timestamp" />
        </fieldset>

        <fieldset name="shipping" source="Magento\Customer\Model\ResourceModel\Address\Collection">
            <reference fieldset="customer" from="entity_id" to="default_shipping"/>
            <field name="full" xsi:type="searchable" dataType="text" handler="ShippingAddressHandler"/>
        </fieldset>

        <fieldset name="billing" source="Magento\Customer\Model\ResourceModel\Address\Collection"
                  provider="Magento\Customer\Model\Indexer\Address\AttributeProvider">
            <reference fieldset="customer" from="entity_id" to="default_billing"/>
            <field name="full" xsi:type="searchable" dataType="text" handler="BillingAddressHandler"/>
            <field name="firstname" xsi:type="searchable" dataType="varchar"/>
            <field name="lastname" xsi:type="searchable" dataType="varchar"/>
            <field name="telephone" xsi:type="searchable" dataType="varchar"/>
            <field name="postcode" xsi:type="searchable" dataType="varchar"/>
            <field name="country_id" xsi:type="filterable" dataType="varchar"/>
            <field name="region" xsi:type="searchable" dataType="varchar"/>
            <field name="street" xsi:type="searchable" dataType="varchar"/>
            <field name="city" xsi:type="searchable" dataType="varchar"/>
            <field name="fax" xsi:type="searchable" dataType="varchar"/>
            <field name="vat_id" xsi:type="searchable" dataType="varchar"/>
            <field name="company" xsi:type="searchable" dataType="varchar"/>
        </fieldset>

        <saveHandler class="Magento\Framework\Indexer\SaveHandler\Grid"/>
        <structure class="Magento\Framework\Indexer\GridStructure"/>
    </indexer>
</config>

fieldset.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Object/etc/fieldset.xsd">
    <scope id="global">
        <fieldset id="customer_account">
            <field name="prefix">
                <aspect name="create" />
                <aspect name="update" />
                <aspect name="name" />
            </field>
            <field name="corporate_id">
                <aspect name="create" />
                <aspect name="update" />
            </field>
            <field name="firstname">
                <aspect name="create" />
                <aspect name="update" />
                <aspect name="name" />
            </field>
            <field name="middlename">
                <aspect name="create" />
                <aspect name="update" />
                <aspect name="name" />
            </field>
            <field name="lastname">
                <aspect name="create" />
                <aspect name="update" />
                <aspect name="name" />
            </field>
            <field name="suffix">
                <aspect name="create" />
                <aspect name="update" />
                <aspect name="name" />
            </field>
            <field name="email">
                <aspect name="create" />
                <aspect name="update" />
            </field>
            <field name="password">
                <aspect name="create" />
            </field>
            <field name="confirmation">
                <aspect name="create" />
            </field>

        </fieldset>
    </scope>
</config>

 

Dúvidas? Faça um comentário logo abaixo ou envie uma mensagem clicando aqui.

O seu endereço de e-mail não será publicado.