How To

Magento 2: How to Add Image Upload Field in System Configuration?

Hello Magento Friends,

Today’s Magento 2 tutorial will teach you How to Add an Image Upload Field in System Configuration?

Customization is the prime feature of Magento. Users can customize almost anything while working with Magento 2. System configuration provides various options to control the website’s functions. You can add custom options to system configuration as and when required.

Here, we will add an image upload field in the system configuration in Magento 2. Let’s check out the steps.

Steps to Add Image Upload Field in Magento 2 System Configuration:

Step 1: Initially, you need to create a field in the system.xml file, at the path given below.

app/code/Vendor/Extension/etc/adminhtml/system.xml

Use the following code snippet 

<field id="image" translate="label" type="image" sortOrder="20" showInDefault="1" showInWebsite="1">
      <label>Upload Image</label>
      <backend_model>Vendor\Extension\Model\Config\Backend\Image</backend_model>
      <base_url type="media">extensionname/foldername/</base_url>
</field>

Step 2: Next you need to backend the model file Image.php. For that go to the below path

Vendor\Extension\Model\Config\Backend\Image.php

And add the code as follows

<?php

namespace Vendor\Extension\Model\Config\Backend;

class Image extends \Magento\Config\Model\Config\Backend\Image
{   
    const UPLOAD_DIR = 'yourfolder';

    /**
    * Return path to directory for upload file
    *
    * @return string
    * @throw \Magento\Framework\Exception\LocalizedException
    */    protected function _getUploadDir()
    {
        return $this->_mediaDirectory->getAbsolutePath($this->_appendScopeInfo(self::UPLOAD_DIR));
    }

    protected function _addWhetherScopeInfo()
    {
        return true;
    }

    /**
    * Getter for allowed extensions of uploaded files.
    *
    * @return string[]
    */    protected function _getAllowedExtensions()
    {
        return ['jpg', 'jpeg', 'gif', 'png', 'svg'];
    }
    protected function getTmpFileName()
    {
        $tmpName = null;
        if (isset($_FILES['groups']))
        {
            $tmpName = $_FILES['groups']['tmp_name'][$this->getGroupId()]['fields'][$this->getField()]['value'];
        }
        else
        {
            $tmpName = is_array($this->getValue()) ? $this->getValue()['tmp_name'] : null;
        }
        return $tmpName;
    }
    public function beforeSave()
    {
        $value = $this->getValue();
        $deleteFlag = is_array($value) && !empty($value['delete']);
        if ($this->isTmpFileAvailable($value) && $imageName = $this->getUploadedImageName($value))
        {
            $fileTmpName = $this->getTmpFileName();
            if ($this->getOldValue() && ($fileTmpName || $deleteFlag))
            {
                $this->_mediaDirectory->delete(self::UPLOAD_DIR . '/' . $this->getOldValue());
            }
        }
        return parent::beforeSave();
    }
    private function isTmpFileAvailable($value)
    {
        return is_array($value) && isset($value[0]['tmp_name']);
    }
    
    private function getUploadedImageName($value)
    {
        if (is_array($value) && isset($value[0]['name']))
        {
            return $value[0]['name'];
        }
        return '';
    }   
}

Once you perform the above steps successfully, the image upload field is added to Magento 2 system configuration as shown below.

Conclusion:

Hence, you have learned How to Add an Image Upload Field in System Configuration in Magento 2. Same way Add Dynamic System Configuration Field in Magento 2. If you face any hardship, let me know through the comment box. Share the article with your friends and stay in touch with us for more.

Happy Coding!

Click to rate this post!
[Total: 5 Average: 3.8]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

3 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

5 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

5 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

6 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

7 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago