Magento – Magento2 – Can not save value of custom column in table customer_entity

attributescustomereavmagento2

I want to add new column, let's call it test, to customer_entity table.

I managed to add the column to the table but values aren't saved for this column when I write something like:

$customer->setData("test", "something");
$customer->save();

The code I used to add the new column in my module's InstallSchema.php:

$eavTable = $installer->getTable('customer_entity');
$columns = [
    'test' => [
        'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
        'length' => '6',
        'nullable' => false,
        'default' => null,
        'comment' => 'test',
    ]
];
foreach ($columns as $name => $definition) {
    $connection->addColumn($eavTable, $name, $definition);
}
$installer->endSetup();

Best Answer

This method used to work with Magento 1, but not in Magento 2. It's true that Magento 2 uses legacy models (that extend from Magento\Framework\DataObject), but it's not safe to rely on this anymore if you want to create future-proof extensions. You should rely on Service Contracts, Data Models and their added functionality for this.

What you are looking for are indeed EAV attributes (which can be accessed using the getCustomAttribute()-method that is declared in Magento\Customer\Api\Data\CustomerInterface), or extension attributes (which allow third party developers to add extra 'stuff' to data models by using interceptors).

Depending on your needs you have to pick one of those.

Rewriting a core class is (like in Magento 1) a thing you should avoid as much as possible in Magento 2. To get your task done, learn getCustomAttribute() and getExtensionAttribute() and how to use them. Magento added a lot more abstraction in Magento 2 to make it more flexible than Magento 1.

More information: http://devdocs.magento.com/guides/v2.1/extension-dev-guide/attributes.html

Related Topic