Magento 2.3 : How to create product attribute via declarative schema?
I wrote an entire blog post about this. It is quite extensive and goes into detail about all of the intricacies: https://markshust.com/2019/02/19/create-product-attribute-data-patch-magento-2.3-declarative-schema/
That said, here is the final class of code you can work with:
<?php
namespace Acme\Foo\Setup\Patch\Data;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
class AddAlternativeColorAttribute implements DataPatchInterface
{
/** @var ModuleDataSetupInterface */
private $moduleDataSetup;
/** @var EavSetupFactory */
private $eavSetupFactory;
/**
* @param ModuleDataSetupInterface $moduleDataSetup
* @param EavSetupFactory $eavSetupFactory
*/
public function __construct(
ModuleDataSetupInterface $moduleDataSetup,
EavSetupFactory $eavSetupFactory
) {
$this->moduleDataSetup = $moduleDataSetup;
$this->eavSetupFactory = $eavSetupFactory;
}
/**
* {@inheritdoc}
*/
public function apply()
{
/** @var EavSetup $eavSetup */
$eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]);
$eavSetup->addAttribute('catalog_product', 'alternative_color', [
'type' => 'int',
'label' => 'Alternative Color',
'input' => 'select',
'used_in_product_listing' => true,
'user_defined' => true,
]);
}
/**
* {@inheritdoc}
*/
public static function getDependencies()
{
return [];
}
/**
* {@inheritdoc}
*/
public function getAliases()
{
return [];
}
}