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

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

6 days ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

2 weeks ago

Managing Browser Events and Navigation in Shopify Remix: useBeforeUnload, useHref, and useLocation Hooks

Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…

2 weeks ago

Ultimate Guide to Hiring a Top Shopify Development Agency

Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…

2 weeks ago