How to Create Image Upload Field in the Custom Module Using UI Component?

4

In this blog, we will learn How to create the Image Upload field in the custom module using the UI Component.

Always choosing the UI component is the best practice to create a module because I suggest that it is the best way to create the module or Magento Extension.

Magento 2 UI Component form provides various options to display many form input fields and an image upload field is one of them.

You also need filter out Off-Stock products when you working on it as project requirements.

In this below example we already have a brand module and we have just highlighted the relevant sections on the image upload field also assumes that you have a basic understanding of the Magento 2 UI Component so you can easily copy the code and put it in the correct place.

Here, you can see that you need to modify or create some of the files in your module so you can see the image upload field and fulfilled your module requirement.

Step 1: Add an Image Upload field in the admin form

First, open the admin_branddetails_fields.xml from the app/code/Yournamespace/Modulename/view/adminhtml/ui_component

The fileUploader component works internally by using a jQuery file uploader.

To show the image field we need to define the field details in UI Component as you can see in the below code.

We need to define some of the required options in the configuration. Let’s take an example:

  • formElement – It should be specify as fileUploader
  • elementTmpl – It’s a display image upload field from the template file.
  • maxFileSize – It allowed File Size in the custom form
  • uploaderConfig – It’s an Ajax Controller URL that handles the upload function.

*** Add this code in the fieldset ***

<field name="brand_image">
	<argument name="data" xsi:type="array">
		<item name="config" xsi:type="array">
			<item name="dataType" xsi:type="string">string</item>
			<item name="source" xsi:type="string">Branddetails</item>
			<item name="label" xsi:type="string" translate="true">Brand Image</item>
			<item name="visible" xsi:type="boolean">true</item>
			<item name="formElement" xsi:type="string">fileUploader</item>
			<item name="previewTmpl" xsi:type="string">Yournamespace/Modulename/image-preview</item>
			<item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
			<item name="required" xsi:type="boolean">false</item>
			<item name="uploaderConfig" xsi:type="array">										
				<item name="url" xsi:type="url" path="brand/branddetails/upload"/>
			</item>
		</item>
	</argument>
</field>

Step 2: Now, create the controller or modify the controller which help to save uploaded image file.

Create Upload.php in the following path app/code/Yournamespace/Modulename/Controller/Adminhtml/Branddetails

<?php
namespace Yournamespace\Modulename\Controller\Adminhtml\Branddetails;
use Magento\Framework\Controller\ResultFactory;

class Upload extends \Magento\Backend\App\Action
{
	protected $imageUploader;

	public function __construct(
		\Magento\Backend\App\Action\Context $context,
		\Magento\Catalog\Model\ImageUploader $imageUploader
	) {		
		parent::__construct($context);
		$this->imageUploader = $imageUploader;
	}

	protected function _isAllowed()
	{
		return $this->_authorization->isAllowed('Yournamespace_Modulename::branddetails');
	}

	public function execute()
	{
		try {
			$result = $this->imageUploader->saveFileToTmpDir('brand_image');
			$result['cookie'] = [
				'name' => $this->_getSession()->getName(),
				'value' => $this->_getSession()->getSessionId(),
				'lifetime' => $this->_getSession()->getCookieLifetime(),
				'path' => $this->_getSession()->getCookiePath(),
				'domain' => $this->_getSession()->getCookieDomain(),
			];
		} catch (\Exception $e) {
			$result = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
		}
		return $this->resultFactory->create(ResultFactory::TYPE_JSON)->setData($result);
	}
}

Step 3: Now, create template which show preview of the uploaded image.

Create image-preview.html in the following folder app/code/Yournamespace/Modulename/view/adminhtml/web/template/image-preview.html

<div class="file-uploader-summary">
	<div class="file-uploader-preview">
		<a attr="href: $parent.getFilePreview($file)" target="_blank">
			<img class="preview-image" tabindex="0" event="load: $parent.onPreviewLoad.bind($parent)" attr="src: $parent.getFilePreview($file),alt: $file.name">
		</a>
		
		<div class="actions">
			<button type="button" class="action-remove" data-role="delete-button" attr="title: $t('Delete image')" click="$parent.removeFile.bind($parent, $file)">
				<span translate="'Delete image'"/>
			</button>
		</div>
	</div>
	<div class="file-uploader-filename" text="$file.name"/>
	<div class="file-uploader-meta">
		<text args="$file.previewWidth"/>x<text args="$file.previewHeight"/>
	</div>
</div>

Step 4: Modify the Model to customize getData() method.

Open the DataProvider.php from the following path: app/code/Yournamespace/Modulename/Model/Branddetails

public function getData()
{	   
	if (isset($this->_loadedData)) {
		return $this->_loadedData;
	}
	$items = $this->collection->getItems();
	
	foreach ($items as $brand) {			
		$brandData = $brand->getData();
		$brand_img = $brandData['brand_image'];
		$brand_img_url = $brandData['brand_image_url'];
		unset($brandData['brand_image']);
		unset($brandData['brand_image_url']);
		$brandData['brand_image'][0]['name'] = $brand_img;
		$brandData['brand_image'][0]['url'] = $brand_img_url;			
		$this->_loadedData[$brand->getEntityId()] = $brandData;		
	}
	
	return $this->_loadedData;
}

Above are all the steps to create an Image Upload field in the custom module using UI Component in Magento 2. I hope you can able to create image upload field in your module if you face any kind of issues then please let me know I will definitely help you as much as I can.

If you tested this code and get proper output then I can asum that I am working good for you developer. There is too many pros of Magento development. You can learn more about pros and cons of Magento with Shopify.

About the author

I’m Magento Certified Developer having quite 5 years of commercial development expertise in Magento as well as in Shopify. I’ve worked primarily with the Magento and Shopify e-commerce platform, managing the complexities concerned in building e-commerce solutions tailored to a client’s specific desires.

Related Posts

2 Responses

Leave a Reply