7

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!

4

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.

  • Thanks for this answer, Raul. Sadly, this is not the way I wanted to do it (even though I ended up doing so this way). – PauGNU May 16 '17 at 14:31

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.