Can Yildirim's Blog

How to create image role on Magento 2 ( + GraphQL )

October 02, 2021

Image roles help frontend developers to use particular roles for particular mission. Magento has default roles like smaill, thumbnail image and base image etc. This can be added from Magento admin via Stores > Attributes > Product > Add New Attribute


Alternatively you can use following code as data patch.

<?php namespace Foo\Bar\Setup\Patch\Data; use Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface; use Magento\Eav\Setup\EavSetup; use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Setup\Patch\DataPatchInterface; class AddBackgroundImage implements DataPatchInterface { /** * @var ModuleDataSetupInterface */ private $moduleDataSetup; /** * @var \Magento\Eav\Setup\EavSetupFactory */ private $eavSetupFactory; public function __construct( ModuleDataSetupInterface $moduleDataSetup, \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory ) { $this->moduleDataSetup = $moduleDataSetup; $this->eavSetupFactory = $eavSetupFactory; } public static function getDependencies() { return []; } public function getAliases() { return []; } public function apply() { /** @var EavSetup $eavSetup */ $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]); $eavSetup->addAttribute( \Magento\Catalog\Model\Product::ENTITY, 'background_image', [ 'type' => 'varchar', 'label' => 'Background Image', 'input' => 'media_image', 'frontend' => \Magento\Catalog\Model\Product\Attribute\Frontend\Image::class, 'required' => false, 'sort_order' => 3, 'global' => ScopedAttributeInterface::SCOPE_STORE, ] ); } }

Here you go we have another image role appearing on our product images.



We’re in a new era that we do cool things with Magento. GraphQL is one of them. So how do we make new image_role visible for GraphQL ?

We just need to add a file etc/schema.graphqls that’s extending ProductInterface.

interface ProductInterface { background_image: ProductImage @doc(description: "The relative path to the background_image, which is used on catalog pages.") @resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\Product\\ProductImage") }

We use an existing resolver here for ProductImage resolver here as it does the job well.

Dont forget to follow @DailyMagento on Twitter.

Written by Can Yildirim who lives in London. Full Stack Software Engineer. Follow me on Twitter Linkedin

© 2021,