Magento – Add an image product attribute in Magento 2 in module setup

-setupimagemagento2product

I've been trying to find an article/question related to the creation of an 'image' type attribute for a product in Magento 2. That is: having just a browse field where the user can upload an image (something similar to the category image upload).

So far I've found this:
create product image attribute in magento2

But it doesn't seem to describe the whole way on how to do it. Is it really necessary to create a custom class to manage this?

Thanks!

Best Answer

You can add and extra attribute image to product entity using an InstallData / UpgradeData file in your module.

Have a look to the following example:

<?php

// vendor/ModuleName/Setup/InstallData.php or
// app/code/vendor/ModuleName/Setup/InstallData.php

use Magento\Catalog\Model\Product;
use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{

/**
 * @var EavSetupFactory
 */
private $eavSetupFactory;

/**
 * InstallData constructor.
 */
public function __construct(
    EavSetupFactory $eavSetupFactory
)
{
    $this->eavSetupFactory = $eavSetupFactory;
}

/**
 * Installs data for a module
 *
 * @param ModuleDataSetupInterface $setup
 * @param ModuleContextInterface   $context
 *
 * @return void
 */
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
    $setup->startSetup();

    /** @var \Magento\Eav\Setup\EavSetup $eavSetup */
    $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

    $eavSetup->addAttribute(
        Product::ENTITY,
        'mouseover_image',
        [
            'type'                    => 'varchar',
            'label'                   => 'Mouseover',
            'input'                   => 'media_image',
            'frontend'                => 'Magento\Catalog\Model\Product\Attribute\Frontend\Image',
            'required'                => false,
            'global'                  => ScopedAttributeInterface::SCOPE_STORE,
            'used_in_product_listing' => true,
        ]);
      $setup->endSetup();
    }
}

I am using this to add an attribute called mouseover_image to the product entity.

Then I can upload any image and assign the attribute or role to it

Add Image attribute to product in Magento 2

Hope it helps.

Related Topic