Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
DEV

Upload an image from Customer Custom Tab in Magento 2 Admin

Here we’ll learn how to upload an Image from customer edit section in Magento 2.

Step 1: Create a custom Form Tab in Customer Edit Section.

Follow the previous blog:

How To Create Tab With Form Fields In Admin Customer Edit Section Magento 2

Add the image field in app/code/Webkul/CustomerEdit/Block/Adminhtml/Customer/Edit/Tabs.php

// Here, we have used the sample file name. You can also use your filename if it is stored in database. Otherwise, value can be ''.
$fileName = 'File-1672040915.png';
$fieldset->addField(
    'custom_image_field',
    'image',
    [
        'name' => 'custom_image_field',
        'label' => __('My Image'),
        'title' => __('My Image'),
        'class' => 'custom_image',
        'data-form-part' => $this->getData('target_form'),
        'value' => 'customimage/image/'.$fileName,
        'note' => __('Allowed image types: jpg,jpeg,gif,png')
        ]
);

Create Child Block: app/code/Webkul/CustomerEdit/Block/Adminhtml/Customer/Edit/AdditionalBlock.php

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomerEdit
 * @author    Webkul
 * @copyright Copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\CustomerEdit\Block\Adminhtml\Customer\Edit\Tab;

class AdditionalBlock extends \Magento\Config\Block\System\Config\Form\Field
{
    const JS_TEMPLATE = 'customer/js.phtml';

    /**
     * @param \Magento\Backend\Block\Widget\Context $context
     * @param array                                 $data
     */
    public function __construct(
        \Magento\Backend\Block\Widget\Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

    /**
     * Set JS template to itself.
     *
     * @return $this
     */
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        if (!$this->getTemplate()) {
            $this->setTemplate(static::JS_TEMPLATE);
        }

        return $this;
    }
}

Now Create Template file : app/code/Webkul/CustomerEdit/view/adminhtml/templates/customer/js.phtml

<!-- you need to add form attribute in image and file type fields to work properly. -->
<script>
    require([
        "jquery",

    ], function($){
    	$("input[type='file']").attr('form','customer_form');
    });
</script>

Now we can upload the image by using the adminhtml_customer_save_after or other dispatch events.

I am going to upload through adminhtml_customer_save_after dispatch event.

Create : app/code/Webkul/CustomerEdit/etc/events.xml

<?xml version="1.0"?>
<!--
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomForm
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="adminhtml_customer_save_after">
        <observer name="webkul_adminhtml_customer_save_after_observer" instance="Webkul\CustomForm\Observer\AdminhtmlCustomerSaveAfterObserver" />
    </event>
</config>

Now create and Observer :
app/code/Webkul/CustomForm/Observer/AdminhtmlCustomerSaveAfterObserver.php

<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_CustomerEdit
 * @author    Webkul
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\CustomerEdit\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;

class AdminhtmlCustomerSaveAfterObserver implements ObserverInterface
{
    /**
     * File Uploader factory.
     *
     * @var \Magento\MediaStorage\Model\File\UploaderFactory
     */
    protected $_fileUploaderFactory;

    protected $_mediaDirectory;

    /**
     * @param Filesystem                                       $filesystem,
     * @param \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
     */
    public function __construct(
        Filesystem $filesystem,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory
    ) {
        $this->_mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
        $this->_fileUploaderFactory = $fileUploaderFactory;
    }

    /**
     * admin customer save after event handler.
     *
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $target = $this->_mediaDirectory->getAbsolutePath('customimage/image/');
        try {
            /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
            $uploader = $this->_fileUploaderFactory->create(
                ['fileId' => 'custom_image_field']
            );
            $uploader->setAllowedExtensions(
                ['jpg', 'jpeg', 'gif', 'png']
            );
            $uploader->setAllowRenameFiles(true);
            $result = $uploader->save($target);

            // Here, you can write your code to save the value in the database.

        } catch(\Exception $e) {
            return '';
        }

        return $this;
    }
}
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


4 comments

  • andrei
    • Demo3 Last
  • Riyas Muhammed
  • Varthini
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home