Magento 2 attribute image multiple

Magento 2 attribute image multiple

September 29, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Magento 2 attribute image multiple

Handling Multiple Product Images in Magento 2

Hello there! I hope this post finds you well. Today, we’re going to tackle an interesting challenge related to product images in Magento 2. Our friend here is dealing with an API that sends multiple images for a single entity, and they’re looking for the most efficient way to save and display these images.

Let’s dive right into it!

The Current Scenario

Our developer has already implemented a mechanism to fetch and save one main image using the built-in EAV attribute. However, when the API starts sending multiple images, things get a bit complicated.

The current approach involves creating additional fields like image2, image3, etc., in the entity to store these extra images. While this might work for a small number of images, it becomes impractical as the count increases, especially since the API can send up to 10 images at a time.

The Problem at Hand

The primary issues here are:

  • Storage Inefficiency: Creating multiple fields for each image is not an optimal solution. It leads to unnecessary database bloat and increased complexity.
  • Display Concerns: Displaying these images in the backend becomes cumbersome as you need to manage a list of input fields.
  • Performance Issues: Fetching, processing, and displaying 10 images at once can impact performance.

The Magento Approach

Magento has built-in features that make handling multiple product images a breeze. We’ll leverage two key components:

The media gallery in Magento is designed to handle multiple images for a single entity elegantly. It allows you to upload and manage images for products, categories, or other entities.

To use the media gallery, you need to create an attribute that references a gallery of images rather than a single image file. This attribute can be associated with your existing entity.

Let’s create a custom attribute that will reference the image gallery:

  1. Navigate to Stores > Attributes > Product.
  2. Click on “New Attribute”.
  3. Set the following properties:
    • Attribute Code: multiple_images
    • Default Value: Leave empty
    • Scope: Global
    • Value Required: No
    • Input Type for Store Owner: Media Image (or Upload File)
  4. Click on “Save Attribute”.

Implementing the Solution

Now, let’s modify your controller to save these images in a gallery:

public function saveAction()
{
    // ... existing code ...

    case 'photos':
        $imageUris = [];
        foreach ($retailerData['photos'] as $item) {
            if (isset($item['publicUrl'])) {
                $imageUrl = $item['publicUrl'];
                $fileName = pathinfo($imageUrl, PATHINFO_BASENAME);
                $newFileName = $this->getMediaSellerPath() . DIRECTORY_SEPARATOR . $fileName;
                $result = $this->fileSystem->readFile($imageUrl, $newFileName);
                if ($result) {
                    $imageUris[] = '/media/seller/' . $fileName;
                }
            }
        }

        // Save images to the gallery
        if (!empty($imageUris)) {
            $galleryFactory = $this->getGalleryFactory();
            $gallery = $galleryFactory->create();
            $images = $gallery->saveImages($model, $imageUris);

            // Set the image gallery in the entity's attribute
            $model->setData('multiple_images', $images);
        }

    break;

    // ... remaining code ...
}

Displaying the Images

To display these images in the backend, you can use a Media Gallery component:

  1. In your admin form XML file, add the following snippet inside your form tag:
<referenceBlock name="product_form_data">
    <block class="Magento\Cms\Block\Adminhtml\Page\Edit\Tab\Main" name="multiple_images">
        <arguments>
            <argument name="data" xsi:type="array">
                <item name="formFieldName" xsi:type="string">multiple_images</item>
            </argument>
        </arguments>
    </block>
</referenceBlock>
  1. In your template file, add the following to display the images:
<div class="admin__field field-image-gallery">
    <label class="admin__label field-label" for="multiple_images">{{trans 'Multiple Images'}}:</label>
    <div class="admin__field-control gallery-images">
        {{block class="Magento\Catalog\Block\Adminhtml\Product\Helper\Form\ImageUploader"
                 name="product_image_uploader"}
            template="Magento_Catalog::product/image_uploader.phtml"
            media_url="{{var media_url}}"
            images='
                <div id="gallery_images">
                    {{block class="Magento\Backend\Block\Widget\Grid" name="product_gallery_grid" as="product_gallery_grid"}}
                        <arguments>
                            <argument name="images" xsi:type="array">
                                <item name="multiple_images" xsi:type="string">{{var multiple_images}}</item>
                            </argument>
                        </arguments>
                    {{block class="Magento\Backend\Block\Widget\Grid" name="product_gallery_grid" as="product_gallery_grid"}}
                </div>
            '
            uploader_name="gallery_images_uploader"
        />
    </div>
</div>

Conclusion

And there you have it! By leveraging Magento’s built-in media gallery feature, we’ve managed to handle multiple images for a single entity efficiently. This approach is much more scalable and maintainable than creating separate fields for each image.

Remember that the key lies in using the multiple_images attribute to reference the gallery of images rather than trying to save them as individual files or attributes.

I hope this helps you solve your challenge! If you have any further questions, feel free to reach out. For more in-depth Magento tutorials and guides, head over to Laravel Company.

Magento 2 Catalog Database Performance

Our network