Magento2 : Admin module Image upload code to display form





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







4















I have magento2 admin custom module with image upload functionality. I want to upload image from admin. what code should apply for display image field in from, upload image, also image display in edit action.



Thanks



File Path : appcode[Vendor][Module]BlockAdminhtmlEmpEditTabMain.php



    /**
* Prepare form
*
* @return $this
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function _prepareForm()
{
$model = $this->_coreRegistry->registry('emp_post');

$isElementDisabled = false;

/** @var MagentoFrameworkDataForm $form */
$form = $this->_formFactory->create();

$form->setHtmlIdPrefix('page_');

$fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Employee Information')]);

if ($model->getId()) {
$fieldset->addField('customer_id', 'hidden', ['name' => 'customer_id']);
}

$fieldset->addField(
'firstname',
'text',
[
'name' => 'firstname',
'label' => __('First Name'),
'title' => __('First Name'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$fieldset->addField(
'lastname',
'text',
[
'name' => 'lastname',
'label' => __('Last Name'),
'title' => __('Last Name'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$fieldset->addField(
'email',
'text',
[
'name' => 'email',
'label' => __('Email Address'),
'title' => __('Email Address'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);


$fieldset->addField(
'image',
'image',
array(
'name' => 'image',
'label' => __('Image'),
'title' => __('Image')
)
);

$fieldset->addField(
'telephone',
'text',
[
'name' => 'telephone',
'label' => __('Telephone'),
'title' => __('Telephone'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$dateFormat = $this->_localeDate->getDateFormat(
IntlDateFormatter::SHORT
);

$fieldset->addField(
'dob',
'date',
[
'name' => 'dob',
'label' => __('Date of birth'),
'date_format' => $dateFormat,
'disabled' => $isElementDisabled,
'class' => 'validate-date validate-date-range date-range-custom_theme-from'
]
);

$fieldset->addField(
'is_active',
'select',
[
'label' => __('Status'),
'title' => __('Status'),
'name' => 'is_active',
'required' => true,
'options' => $this->_status->getOptionArray(),
'disabled' => $isElementDisabled
]
);
if (!$model->getId()) {
$model->setData('is_active', $isElementDisabled ? '0' : '1');
}


if($model->getData('image')){
$model->setData('image','learning/images'.$model->getData('image'));
}

$form->setValues($model->getData());
$this->setForm($form);

return parent::_prepareForm();
}









share|improve this question

























  • The module developed darshanbhavsar.wordpress.com/2015/02/11/magento-2-custom-module looks to have everything you are looking for.

    – Imran Zahoor
    Jun 5 '16 at 19:55


















4















I have magento2 admin custom module with image upload functionality. I want to upload image from admin. what code should apply for display image field in from, upload image, also image display in edit action.



Thanks



File Path : appcode[Vendor][Module]BlockAdminhtmlEmpEditTabMain.php



    /**
* Prepare form
*
* @return $this
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function _prepareForm()
{
$model = $this->_coreRegistry->registry('emp_post');

$isElementDisabled = false;

/** @var MagentoFrameworkDataForm $form */
$form = $this->_formFactory->create();

$form->setHtmlIdPrefix('page_');

$fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Employee Information')]);

if ($model->getId()) {
$fieldset->addField('customer_id', 'hidden', ['name' => 'customer_id']);
}

$fieldset->addField(
'firstname',
'text',
[
'name' => 'firstname',
'label' => __('First Name'),
'title' => __('First Name'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$fieldset->addField(
'lastname',
'text',
[
'name' => 'lastname',
'label' => __('Last Name'),
'title' => __('Last Name'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$fieldset->addField(
'email',
'text',
[
'name' => 'email',
'label' => __('Email Address'),
'title' => __('Email Address'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);


$fieldset->addField(
'image',
'image',
array(
'name' => 'image',
'label' => __('Image'),
'title' => __('Image')
)
);

$fieldset->addField(
'telephone',
'text',
[
'name' => 'telephone',
'label' => __('Telephone'),
'title' => __('Telephone'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$dateFormat = $this->_localeDate->getDateFormat(
IntlDateFormatter::SHORT
);

$fieldset->addField(
'dob',
'date',
[
'name' => 'dob',
'label' => __('Date of birth'),
'date_format' => $dateFormat,
'disabled' => $isElementDisabled,
'class' => 'validate-date validate-date-range date-range-custom_theme-from'
]
);

$fieldset->addField(
'is_active',
'select',
[
'label' => __('Status'),
'title' => __('Status'),
'name' => 'is_active',
'required' => true,
'options' => $this->_status->getOptionArray(),
'disabled' => $isElementDisabled
]
);
if (!$model->getId()) {
$model->setData('is_active', $isElementDisabled ? '0' : '1');
}


if($model->getData('image')){
$model->setData('image','learning/images'.$model->getData('image'));
}

$form->setValues($model->getData());
$this->setForm($form);

return parent::_prepareForm();
}









share|improve this question

























  • The module developed darshanbhavsar.wordpress.com/2015/02/11/magento-2-custom-module looks to have everything you are looking for.

    – Imran Zahoor
    Jun 5 '16 at 19:55














4












4








4


5






I have magento2 admin custom module with image upload functionality. I want to upload image from admin. what code should apply for display image field in from, upload image, also image display in edit action.



Thanks



File Path : appcode[Vendor][Module]BlockAdminhtmlEmpEditTabMain.php



    /**
* Prepare form
*
* @return $this
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function _prepareForm()
{
$model = $this->_coreRegistry->registry('emp_post');

$isElementDisabled = false;

/** @var MagentoFrameworkDataForm $form */
$form = $this->_formFactory->create();

$form->setHtmlIdPrefix('page_');

$fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Employee Information')]);

if ($model->getId()) {
$fieldset->addField('customer_id', 'hidden', ['name' => 'customer_id']);
}

$fieldset->addField(
'firstname',
'text',
[
'name' => 'firstname',
'label' => __('First Name'),
'title' => __('First Name'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$fieldset->addField(
'lastname',
'text',
[
'name' => 'lastname',
'label' => __('Last Name'),
'title' => __('Last Name'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$fieldset->addField(
'email',
'text',
[
'name' => 'email',
'label' => __('Email Address'),
'title' => __('Email Address'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);


$fieldset->addField(
'image',
'image',
array(
'name' => 'image',
'label' => __('Image'),
'title' => __('Image')
)
);

$fieldset->addField(
'telephone',
'text',
[
'name' => 'telephone',
'label' => __('Telephone'),
'title' => __('Telephone'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$dateFormat = $this->_localeDate->getDateFormat(
IntlDateFormatter::SHORT
);

$fieldset->addField(
'dob',
'date',
[
'name' => 'dob',
'label' => __('Date of birth'),
'date_format' => $dateFormat,
'disabled' => $isElementDisabled,
'class' => 'validate-date validate-date-range date-range-custom_theme-from'
]
);

$fieldset->addField(
'is_active',
'select',
[
'label' => __('Status'),
'title' => __('Status'),
'name' => 'is_active',
'required' => true,
'options' => $this->_status->getOptionArray(),
'disabled' => $isElementDisabled
]
);
if (!$model->getId()) {
$model->setData('is_active', $isElementDisabled ? '0' : '1');
}


if($model->getData('image')){
$model->setData('image','learning/images'.$model->getData('image'));
}

$form->setValues($model->getData());
$this->setForm($form);

return parent::_prepareForm();
}









share|improve this question
















I have magento2 admin custom module with image upload functionality. I want to upload image from admin. what code should apply for display image field in from, upload image, also image display in edit action.



Thanks



File Path : appcode[Vendor][Module]BlockAdminhtmlEmpEditTabMain.php



    /**
* Prepare form
*
* @return $this
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function _prepareForm()
{
$model = $this->_coreRegistry->registry('emp_post');

$isElementDisabled = false;

/** @var MagentoFrameworkDataForm $form */
$form = $this->_formFactory->create();

$form->setHtmlIdPrefix('page_');

$fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Employee Information')]);

if ($model->getId()) {
$fieldset->addField('customer_id', 'hidden', ['name' => 'customer_id']);
}

$fieldset->addField(
'firstname',
'text',
[
'name' => 'firstname',
'label' => __('First Name'),
'title' => __('First Name'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$fieldset->addField(
'lastname',
'text',
[
'name' => 'lastname',
'label' => __('Last Name'),
'title' => __('Last Name'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$fieldset->addField(
'email',
'text',
[
'name' => 'email',
'label' => __('Email Address'),
'title' => __('Email Address'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);


$fieldset->addField(
'image',
'image',
array(
'name' => 'image',
'label' => __('Image'),
'title' => __('Image')
)
);

$fieldset->addField(
'telephone',
'text',
[
'name' => 'telephone',
'label' => __('Telephone'),
'title' => __('Telephone'),
'required' => true,
'disabled' => $isElementDisabled,
'value' =>'abc'
]
);

$dateFormat = $this->_localeDate->getDateFormat(
IntlDateFormatter::SHORT
);

$fieldset->addField(
'dob',
'date',
[
'name' => 'dob',
'label' => __('Date of birth'),
'date_format' => $dateFormat,
'disabled' => $isElementDisabled,
'class' => 'validate-date validate-date-range date-range-custom_theme-from'
]
);

$fieldset->addField(
'is_active',
'select',
[
'label' => __('Status'),
'title' => __('Status'),
'name' => 'is_active',
'required' => true,
'options' => $this->_status->getOptionArray(),
'disabled' => $isElementDisabled
]
);
if (!$model->getId()) {
$model->setData('is_active', $isElementDisabled ? '0' : '1');
}


if($model->getData('image')){
$model->setData('image','learning/images'.$model->getData('image'));
}

$form->setValues($model->getData());
$this->setForm($form);

return parent::_prepareForm();
}






magento2 image-upload






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 5 '16 at 20:12









benmarks

15.3k436105




15.3k436105










asked Oct 12 '15 at 10:15









Suresh ChikaniSuresh Chikani

10.5k53471




10.5k53471













  • The module developed darshanbhavsar.wordpress.com/2015/02/11/magento-2-custom-module looks to have everything you are looking for.

    – Imran Zahoor
    Jun 5 '16 at 19:55



















  • The module developed darshanbhavsar.wordpress.com/2015/02/11/magento-2-custom-module looks to have everything you are looking for.

    – Imran Zahoor
    Jun 5 '16 at 19:55

















The module developed darshanbhavsar.wordpress.com/2015/02/11/magento-2-custom-module looks to have everything you are looking for.

– Imran Zahoor
Jun 5 '16 at 19:55





The module developed darshanbhavsar.wordpress.com/2015/02/11/magento-2-custom-module looks to have everything you are looking for.

– Imran Zahoor
Jun 5 '16 at 19:55










3 Answers
3






active

oldest

votes


















16














You need to create a class to handle your image upload field and show the image once is uploaded.



So create [Namespace][Module]BlockAdminhtml[Entity]HelperImage class



<?php
namespace [Namespace][Module]BlockAdminhtml[Entity]Helper;
use MagentoFrameworkDataFormElementImage as ImageField;
use MagentoFrameworkDataFormElementFactory as ElementFactory;
use MagentoFrameworkDataFormElementCollectionFactory as ElementCollectionFactory;
use MagentoFrameworkEscaper;
use [Namespace][Module]Model[Entity]Image as [Entity]Image;
use MagentoFrameworkUrlInterface;

/**
* @method string getValue()
*/
class Image extends ImageField
{
/**
* image model
*
* @var [Namespace][Module]Model[Entity]Image
*/
protected $imageModel;

/**
* @param [Entity]Image $imageModel
* @param ElementFactory $factoryElement
* @param ElementCollectionFactory $factoryCollection
* @param Escaper $escaper
* @param UrlInterface $urlBuilder
* @param array $data
*/
public function __construct(
[Entity]Image $imageModel,
ElementFactory $factoryElement,
ElementCollectionFactory $factoryCollection,
Escaper $escaper,
UrlInterface $urlBuilder,
$data =
)
{
$this->imageModel = $imageModel;
parent::__construct($factoryElement, $factoryCollection, $escaper, $urlBuilder, $data);
}
/**
* Get image preview url
*
* @return string
*/
protected function _getUrl()
{
$url = false;
if ($this->getValue()) {
$url = $this->imageModel->getBaseUrl().$this->getValue();
}
return $url;
}
}


then create the class that will help you retrieve the image upload path and upload dir



<?php
namespace [Namespace][Module]Model[Entity];
use MagentoFrameworkUrlInterface;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppFilesystemDirectoryList;
class Image
{
/**
* media sub folder
* @var string
*/
protected $subDir = '[namespace]/[module]/[entity]';
/**
* url builder
*
* @var MagentoFrameworkUrlInterface
*/
protected $urlBuilder;
/**
* @var MagentoFrameworkFilesystem
*/
protected $fileSystem;
/**
* @param UrlInterface $urlBuilder
* @param Filesystem $fileSystem
*/
public function __construct(
UrlInterface $urlBuilder,
Filesystem $fileSystem
)
{
$this->urlBuilder = $urlBuilder;
$this->fileSystem = $fileSystem;
}
/**
* get images base url
*
* @return string
*/
public function getBaseUrl()
{
return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]).$this->subDir.'/image';
}
/**
* get base image dir
*
* @return string
*/
public function getBaseDir()
{
return $this->fileSystem->getDirectoryWrite(DirectoryList::MEDIA)->getAbsolutePath($this->subDir.'/image');
}
}


now in your edit for tab add this in the method _prepareForm right after declaring the fieldset



$fieldset->addType('image', '[Namespace][Module]BlockAdminhtml[Entity]HelperImage');


and add your image field like this



$fieldset->addField(
'image_field_name',
'image',
[
'name' => 'image_field_name',
'label' => __('Image field Label'),
'title' => __('Image field Label'),
]
);


In the controller that saves your entity you need to inject in the constructor the following classes



MagentoMediaStorageModelFileUploaderFactory and [Namespace][Module]Model[Entity]Image



So make your class look like this



<?php
use MagentoFrameworkExceptionLocalizedException as FrameworkException;

class ....

protected $uploaderFactory;
protected $imageModel;

public function __construct(
....
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
[Namespace][Module]Model[Entity]Image $imageModel,
....
){
...
$this->uploaderFactory = $uploaderFactory;
$this->imageModel = $imageModel;
...
}


Now, in the same controller add this, before calling $[entity]->save()



$imageName = $this->uploadFileAndGetName('image_field_name', $this->imageModel->getBaseDir(), $data);
$[entity]->setImageFieldName($imageName);


and create this method:



public function uploadFileAndGetName($input, $destinationFolder, $data)
{
try {
if (isset($data[$input]['delete'])) {
return '';
} else {
$uploader = $this->uploaderFactory->create(['fileId' => $input]);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$result = $uploader->save($destinationFolder);
return $result['file'];
}
} catch (Exception $e) {
if ($e->getCode() != MagentoFrameworkFileUploader::TMP_NAME_EMPTY) {
throw new FrameworkException($e->getMessage());
} else {
if (isset($data[$input]['value'])) {
return $data[$input]['value'];
}
}
}
return '';
}


A full example on how to create an entity that supports image and file upload (it's a bit different than described here as it contains an extra class for upload) can be found here






share|improve this answer


























  • given url exension not working. it throw error on screen exception 'MagentoFrameworkExceptionLocalizedException' with message 'Source class "MagentoFrameworkViewElementUiComponentDataProviderCollection" for "MagentoFrameworkViewElementUiComponentDataProviderCollectionFactory" generation does not exist.'

    – Suresh Chikani
    Oct 13 '15 at 8:48











  • @SHPatel. Clear the contents of var/generation. If this problem persists it can for 2 reasons. You either don't have the latest version of Magento 2 or my extension does not work on the latest version. If the problem is my extension I will check it when I have some time.

    – Marius
    Oct 13 '15 at 11:11











  • @Marius, How can we display such image into adminhtml Grid section too? Right now is Default magento 2 is showing it for Product Grid.

    – Praful Rajput
    Oct 13 '15 at 13:29











  • @PrafulRajput. I didn't get to check that part out yet. I have no idea how it's done.

    – Marius
    Oct 13 '15 at 13:38











  • @marius this works in RC 2. One thing you mention adding $fieldset->addType('image', '[Namespace][Module]Adminhtml[Entity]HelperImage'); I am pretty sure you are missing a "Block" callout. [Namespace][Module]BlockAdminhtml[Entity]HelperImage

    – Eirik
    Nov 9 '15 at 20:47



















3














Admin module for basic add update news is here.
In case you are looking for simple image upload solution look at the following snippet which is take from the link.



use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoBackendAppAction;
protected $_fileUploaderFactory;
public function __construct(
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
ActionContext $context
) {
$this->_fileUploaderFactory = $fileUploaderFactory;
parent::__construct($context);
}
public function execute(){
$uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = $this->_objectManager->get('MagentoFrameworkFilesystem')->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath('images/');
$uploader->save($path);
}





share|improve this answer


























  • _filesystem not definded :(

    – fudu
    Oct 30 '18 at 8:48











  • found it, we need to add this to work, also create it in construct() function as well use MagentoFrameworkFilesystem;

    – fudu
    Oct 30 '18 at 8:57











  • Replace _filesystem by $this->_objectManager->get('MagentoFrameworkFilesystem')

    – divya sekar
    30 mins ago



















1














You could add image field in _prepareForm() method of your admin form:



$fieldset->addField(
'imagefieldname',
'image',
array(
'name' => 'imagefieldname',
'label' => __('Image'),
'title' => __('Image')
)

);





share|improve this answer





















  • 1





    @chanresh image field added done but i need to display image preview on form.

    – Suresh Chikani
    Oct 13 '15 at 8:49






  • 1





    If you upload image and save the record then it will show small thumbnail near "Choose File" input file field.

    – Chandresh P.
    Oct 13 '15 at 9:08








  • 1





    I have uplode image and save it but thumbnail image can't display.

    – Suresh Chikani
    Oct 13 '15 at 9:27











  • Please add your code snippet for _prepareForm().

    – Chandresh P.
    Oct 13 '15 at 12:24











  • check my question, question updated with _prepareForm().

    – Suresh Chikani
    Oct 13 '15 at 12:36












Your Answer








StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "479"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f86125%2fmagento2-admin-module-image-upload-code-to-display-form%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









16














You need to create a class to handle your image upload field and show the image once is uploaded.



So create [Namespace][Module]BlockAdminhtml[Entity]HelperImage class



<?php
namespace [Namespace][Module]BlockAdminhtml[Entity]Helper;
use MagentoFrameworkDataFormElementImage as ImageField;
use MagentoFrameworkDataFormElementFactory as ElementFactory;
use MagentoFrameworkDataFormElementCollectionFactory as ElementCollectionFactory;
use MagentoFrameworkEscaper;
use [Namespace][Module]Model[Entity]Image as [Entity]Image;
use MagentoFrameworkUrlInterface;

/**
* @method string getValue()
*/
class Image extends ImageField
{
/**
* image model
*
* @var [Namespace][Module]Model[Entity]Image
*/
protected $imageModel;

/**
* @param [Entity]Image $imageModel
* @param ElementFactory $factoryElement
* @param ElementCollectionFactory $factoryCollection
* @param Escaper $escaper
* @param UrlInterface $urlBuilder
* @param array $data
*/
public function __construct(
[Entity]Image $imageModel,
ElementFactory $factoryElement,
ElementCollectionFactory $factoryCollection,
Escaper $escaper,
UrlInterface $urlBuilder,
$data =
)
{
$this->imageModel = $imageModel;
parent::__construct($factoryElement, $factoryCollection, $escaper, $urlBuilder, $data);
}
/**
* Get image preview url
*
* @return string
*/
protected function _getUrl()
{
$url = false;
if ($this->getValue()) {
$url = $this->imageModel->getBaseUrl().$this->getValue();
}
return $url;
}
}


then create the class that will help you retrieve the image upload path and upload dir



<?php
namespace [Namespace][Module]Model[Entity];
use MagentoFrameworkUrlInterface;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppFilesystemDirectoryList;
class Image
{
/**
* media sub folder
* @var string
*/
protected $subDir = '[namespace]/[module]/[entity]';
/**
* url builder
*
* @var MagentoFrameworkUrlInterface
*/
protected $urlBuilder;
/**
* @var MagentoFrameworkFilesystem
*/
protected $fileSystem;
/**
* @param UrlInterface $urlBuilder
* @param Filesystem $fileSystem
*/
public function __construct(
UrlInterface $urlBuilder,
Filesystem $fileSystem
)
{
$this->urlBuilder = $urlBuilder;
$this->fileSystem = $fileSystem;
}
/**
* get images base url
*
* @return string
*/
public function getBaseUrl()
{
return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]).$this->subDir.'/image';
}
/**
* get base image dir
*
* @return string
*/
public function getBaseDir()
{
return $this->fileSystem->getDirectoryWrite(DirectoryList::MEDIA)->getAbsolutePath($this->subDir.'/image');
}
}


now in your edit for tab add this in the method _prepareForm right after declaring the fieldset



$fieldset->addType('image', '[Namespace][Module]BlockAdminhtml[Entity]HelperImage');


and add your image field like this



$fieldset->addField(
'image_field_name',
'image',
[
'name' => 'image_field_name',
'label' => __('Image field Label'),
'title' => __('Image field Label'),
]
);


In the controller that saves your entity you need to inject in the constructor the following classes



MagentoMediaStorageModelFileUploaderFactory and [Namespace][Module]Model[Entity]Image



So make your class look like this



<?php
use MagentoFrameworkExceptionLocalizedException as FrameworkException;

class ....

protected $uploaderFactory;
protected $imageModel;

public function __construct(
....
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
[Namespace][Module]Model[Entity]Image $imageModel,
....
){
...
$this->uploaderFactory = $uploaderFactory;
$this->imageModel = $imageModel;
...
}


Now, in the same controller add this, before calling $[entity]->save()



$imageName = $this->uploadFileAndGetName('image_field_name', $this->imageModel->getBaseDir(), $data);
$[entity]->setImageFieldName($imageName);


and create this method:



public function uploadFileAndGetName($input, $destinationFolder, $data)
{
try {
if (isset($data[$input]['delete'])) {
return '';
} else {
$uploader = $this->uploaderFactory->create(['fileId' => $input]);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$result = $uploader->save($destinationFolder);
return $result['file'];
}
} catch (Exception $e) {
if ($e->getCode() != MagentoFrameworkFileUploader::TMP_NAME_EMPTY) {
throw new FrameworkException($e->getMessage());
} else {
if (isset($data[$input]['value'])) {
return $data[$input]['value'];
}
}
}
return '';
}


A full example on how to create an entity that supports image and file upload (it's a bit different than described here as it contains an extra class for upload) can be found here






share|improve this answer


























  • given url exension not working. it throw error on screen exception 'MagentoFrameworkExceptionLocalizedException' with message 'Source class "MagentoFrameworkViewElementUiComponentDataProviderCollection" for "MagentoFrameworkViewElementUiComponentDataProviderCollectionFactory" generation does not exist.'

    – Suresh Chikani
    Oct 13 '15 at 8:48











  • @SHPatel. Clear the contents of var/generation. If this problem persists it can for 2 reasons. You either don't have the latest version of Magento 2 or my extension does not work on the latest version. If the problem is my extension I will check it when I have some time.

    – Marius
    Oct 13 '15 at 11:11











  • @Marius, How can we display such image into adminhtml Grid section too? Right now is Default magento 2 is showing it for Product Grid.

    – Praful Rajput
    Oct 13 '15 at 13:29











  • @PrafulRajput. I didn't get to check that part out yet. I have no idea how it's done.

    – Marius
    Oct 13 '15 at 13:38











  • @marius this works in RC 2. One thing you mention adding $fieldset->addType('image', '[Namespace][Module]Adminhtml[Entity]HelperImage'); I am pretty sure you are missing a "Block" callout. [Namespace][Module]BlockAdminhtml[Entity]HelperImage

    – Eirik
    Nov 9 '15 at 20:47
















16














You need to create a class to handle your image upload field and show the image once is uploaded.



So create [Namespace][Module]BlockAdminhtml[Entity]HelperImage class



<?php
namespace [Namespace][Module]BlockAdminhtml[Entity]Helper;
use MagentoFrameworkDataFormElementImage as ImageField;
use MagentoFrameworkDataFormElementFactory as ElementFactory;
use MagentoFrameworkDataFormElementCollectionFactory as ElementCollectionFactory;
use MagentoFrameworkEscaper;
use [Namespace][Module]Model[Entity]Image as [Entity]Image;
use MagentoFrameworkUrlInterface;

/**
* @method string getValue()
*/
class Image extends ImageField
{
/**
* image model
*
* @var [Namespace][Module]Model[Entity]Image
*/
protected $imageModel;

/**
* @param [Entity]Image $imageModel
* @param ElementFactory $factoryElement
* @param ElementCollectionFactory $factoryCollection
* @param Escaper $escaper
* @param UrlInterface $urlBuilder
* @param array $data
*/
public function __construct(
[Entity]Image $imageModel,
ElementFactory $factoryElement,
ElementCollectionFactory $factoryCollection,
Escaper $escaper,
UrlInterface $urlBuilder,
$data =
)
{
$this->imageModel = $imageModel;
parent::__construct($factoryElement, $factoryCollection, $escaper, $urlBuilder, $data);
}
/**
* Get image preview url
*
* @return string
*/
protected function _getUrl()
{
$url = false;
if ($this->getValue()) {
$url = $this->imageModel->getBaseUrl().$this->getValue();
}
return $url;
}
}


then create the class that will help you retrieve the image upload path and upload dir



<?php
namespace [Namespace][Module]Model[Entity];
use MagentoFrameworkUrlInterface;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppFilesystemDirectoryList;
class Image
{
/**
* media sub folder
* @var string
*/
protected $subDir = '[namespace]/[module]/[entity]';
/**
* url builder
*
* @var MagentoFrameworkUrlInterface
*/
protected $urlBuilder;
/**
* @var MagentoFrameworkFilesystem
*/
protected $fileSystem;
/**
* @param UrlInterface $urlBuilder
* @param Filesystem $fileSystem
*/
public function __construct(
UrlInterface $urlBuilder,
Filesystem $fileSystem
)
{
$this->urlBuilder = $urlBuilder;
$this->fileSystem = $fileSystem;
}
/**
* get images base url
*
* @return string
*/
public function getBaseUrl()
{
return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]).$this->subDir.'/image';
}
/**
* get base image dir
*
* @return string
*/
public function getBaseDir()
{
return $this->fileSystem->getDirectoryWrite(DirectoryList::MEDIA)->getAbsolutePath($this->subDir.'/image');
}
}


now in your edit for tab add this in the method _prepareForm right after declaring the fieldset



$fieldset->addType('image', '[Namespace][Module]BlockAdminhtml[Entity]HelperImage');


and add your image field like this



$fieldset->addField(
'image_field_name',
'image',
[
'name' => 'image_field_name',
'label' => __('Image field Label'),
'title' => __('Image field Label'),
]
);


In the controller that saves your entity you need to inject in the constructor the following classes



MagentoMediaStorageModelFileUploaderFactory and [Namespace][Module]Model[Entity]Image



So make your class look like this



<?php
use MagentoFrameworkExceptionLocalizedException as FrameworkException;

class ....

protected $uploaderFactory;
protected $imageModel;

public function __construct(
....
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
[Namespace][Module]Model[Entity]Image $imageModel,
....
){
...
$this->uploaderFactory = $uploaderFactory;
$this->imageModel = $imageModel;
...
}


Now, in the same controller add this, before calling $[entity]->save()



$imageName = $this->uploadFileAndGetName('image_field_name', $this->imageModel->getBaseDir(), $data);
$[entity]->setImageFieldName($imageName);


and create this method:



public function uploadFileAndGetName($input, $destinationFolder, $data)
{
try {
if (isset($data[$input]['delete'])) {
return '';
} else {
$uploader = $this->uploaderFactory->create(['fileId' => $input]);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$result = $uploader->save($destinationFolder);
return $result['file'];
}
} catch (Exception $e) {
if ($e->getCode() != MagentoFrameworkFileUploader::TMP_NAME_EMPTY) {
throw new FrameworkException($e->getMessage());
} else {
if (isset($data[$input]['value'])) {
return $data[$input]['value'];
}
}
}
return '';
}


A full example on how to create an entity that supports image and file upload (it's a bit different than described here as it contains an extra class for upload) can be found here






share|improve this answer


























  • given url exension not working. it throw error on screen exception 'MagentoFrameworkExceptionLocalizedException' with message 'Source class "MagentoFrameworkViewElementUiComponentDataProviderCollection" for "MagentoFrameworkViewElementUiComponentDataProviderCollectionFactory" generation does not exist.'

    – Suresh Chikani
    Oct 13 '15 at 8:48











  • @SHPatel. Clear the contents of var/generation. If this problem persists it can for 2 reasons. You either don't have the latest version of Magento 2 or my extension does not work on the latest version. If the problem is my extension I will check it when I have some time.

    – Marius
    Oct 13 '15 at 11:11











  • @Marius, How can we display such image into adminhtml Grid section too? Right now is Default magento 2 is showing it for Product Grid.

    – Praful Rajput
    Oct 13 '15 at 13:29











  • @PrafulRajput. I didn't get to check that part out yet. I have no idea how it's done.

    – Marius
    Oct 13 '15 at 13:38











  • @marius this works in RC 2. One thing you mention adding $fieldset->addType('image', '[Namespace][Module]Adminhtml[Entity]HelperImage'); I am pretty sure you are missing a "Block" callout. [Namespace][Module]BlockAdminhtml[Entity]HelperImage

    – Eirik
    Nov 9 '15 at 20:47














16












16








16







You need to create a class to handle your image upload field and show the image once is uploaded.



So create [Namespace][Module]BlockAdminhtml[Entity]HelperImage class



<?php
namespace [Namespace][Module]BlockAdminhtml[Entity]Helper;
use MagentoFrameworkDataFormElementImage as ImageField;
use MagentoFrameworkDataFormElementFactory as ElementFactory;
use MagentoFrameworkDataFormElementCollectionFactory as ElementCollectionFactory;
use MagentoFrameworkEscaper;
use [Namespace][Module]Model[Entity]Image as [Entity]Image;
use MagentoFrameworkUrlInterface;

/**
* @method string getValue()
*/
class Image extends ImageField
{
/**
* image model
*
* @var [Namespace][Module]Model[Entity]Image
*/
protected $imageModel;

/**
* @param [Entity]Image $imageModel
* @param ElementFactory $factoryElement
* @param ElementCollectionFactory $factoryCollection
* @param Escaper $escaper
* @param UrlInterface $urlBuilder
* @param array $data
*/
public function __construct(
[Entity]Image $imageModel,
ElementFactory $factoryElement,
ElementCollectionFactory $factoryCollection,
Escaper $escaper,
UrlInterface $urlBuilder,
$data =
)
{
$this->imageModel = $imageModel;
parent::__construct($factoryElement, $factoryCollection, $escaper, $urlBuilder, $data);
}
/**
* Get image preview url
*
* @return string
*/
protected function _getUrl()
{
$url = false;
if ($this->getValue()) {
$url = $this->imageModel->getBaseUrl().$this->getValue();
}
return $url;
}
}


then create the class that will help you retrieve the image upload path and upload dir



<?php
namespace [Namespace][Module]Model[Entity];
use MagentoFrameworkUrlInterface;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppFilesystemDirectoryList;
class Image
{
/**
* media sub folder
* @var string
*/
protected $subDir = '[namespace]/[module]/[entity]';
/**
* url builder
*
* @var MagentoFrameworkUrlInterface
*/
protected $urlBuilder;
/**
* @var MagentoFrameworkFilesystem
*/
protected $fileSystem;
/**
* @param UrlInterface $urlBuilder
* @param Filesystem $fileSystem
*/
public function __construct(
UrlInterface $urlBuilder,
Filesystem $fileSystem
)
{
$this->urlBuilder = $urlBuilder;
$this->fileSystem = $fileSystem;
}
/**
* get images base url
*
* @return string
*/
public function getBaseUrl()
{
return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]).$this->subDir.'/image';
}
/**
* get base image dir
*
* @return string
*/
public function getBaseDir()
{
return $this->fileSystem->getDirectoryWrite(DirectoryList::MEDIA)->getAbsolutePath($this->subDir.'/image');
}
}


now in your edit for tab add this in the method _prepareForm right after declaring the fieldset



$fieldset->addType('image', '[Namespace][Module]BlockAdminhtml[Entity]HelperImage');


and add your image field like this



$fieldset->addField(
'image_field_name',
'image',
[
'name' => 'image_field_name',
'label' => __('Image field Label'),
'title' => __('Image field Label'),
]
);


In the controller that saves your entity you need to inject in the constructor the following classes



MagentoMediaStorageModelFileUploaderFactory and [Namespace][Module]Model[Entity]Image



So make your class look like this



<?php
use MagentoFrameworkExceptionLocalizedException as FrameworkException;

class ....

protected $uploaderFactory;
protected $imageModel;

public function __construct(
....
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
[Namespace][Module]Model[Entity]Image $imageModel,
....
){
...
$this->uploaderFactory = $uploaderFactory;
$this->imageModel = $imageModel;
...
}


Now, in the same controller add this, before calling $[entity]->save()



$imageName = $this->uploadFileAndGetName('image_field_name', $this->imageModel->getBaseDir(), $data);
$[entity]->setImageFieldName($imageName);


and create this method:



public function uploadFileAndGetName($input, $destinationFolder, $data)
{
try {
if (isset($data[$input]['delete'])) {
return '';
} else {
$uploader = $this->uploaderFactory->create(['fileId' => $input]);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$result = $uploader->save($destinationFolder);
return $result['file'];
}
} catch (Exception $e) {
if ($e->getCode() != MagentoFrameworkFileUploader::TMP_NAME_EMPTY) {
throw new FrameworkException($e->getMessage());
} else {
if (isset($data[$input]['value'])) {
return $data[$input]['value'];
}
}
}
return '';
}


A full example on how to create an entity that supports image and file upload (it's a bit different than described here as it contains an extra class for upload) can be found here






share|improve this answer















You need to create a class to handle your image upload field and show the image once is uploaded.



So create [Namespace][Module]BlockAdminhtml[Entity]HelperImage class



<?php
namespace [Namespace][Module]BlockAdminhtml[Entity]Helper;
use MagentoFrameworkDataFormElementImage as ImageField;
use MagentoFrameworkDataFormElementFactory as ElementFactory;
use MagentoFrameworkDataFormElementCollectionFactory as ElementCollectionFactory;
use MagentoFrameworkEscaper;
use [Namespace][Module]Model[Entity]Image as [Entity]Image;
use MagentoFrameworkUrlInterface;

/**
* @method string getValue()
*/
class Image extends ImageField
{
/**
* image model
*
* @var [Namespace][Module]Model[Entity]Image
*/
protected $imageModel;

/**
* @param [Entity]Image $imageModel
* @param ElementFactory $factoryElement
* @param ElementCollectionFactory $factoryCollection
* @param Escaper $escaper
* @param UrlInterface $urlBuilder
* @param array $data
*/
public function __construct(
[Entity]Image $imageModel,
ElementFactory $factoryElement,
ElementCollectionFactory $factoryCollection,
Escaper $escaper,
UrlInterface $urlBuilder,
$data =
)
{
$this->imageModel = $imageModel;
parent::__construct($factoryElement, $factoryCollection, $escaper, $urlBuilder, $data);
}
/**
* Get image preview url
*
* @return string
*/
protected function _getUrl()
{
$url = false;
if ($this->getValue()) {
$url = $this->imageModel->getBaseUrl().$this->getValue();
}
return $url;
}
}


then create the class that will help you retrieve the image upload path and upload dir



<?php
namespace [Namespace][Module]Model[Entity];
use MagentoFrameworkUrlInterface;
use MagentoFrameworkFilesystem;
use MagentoFrameworkAppFilesystemDirectoryList;
class Image
{
/**
* media sub folder
* @var string
*/
protected $subDir = '[namespace]/[module]/[entity]';
/**
* url builder
*
* @var MagentoFrameworkUrlInterface
*/
protected $urlBuilder;
/**
* @var MagentoFrameworkFilesystem
*/
protected $fileSystem;
/**
* @param UrlInterface $urlBuilder
* @param Filesystem $fileSystem
*/
public function __construct(
UrlInterface $urlBuilder,
Filesystem $fileSystem
)
{
$this->urlBuilder = $urlBuilder;
$this->fileSystem = $fileSystem;
}
/**
* get images base url
*
* @return string
*/
public function getBaseUrl()
{
return $this->urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]).$this->subDir.'/image';
}
/**
* get base image dir
*
* @return string
*/
public function getBaseDir()
{
return $this->fileSystem->getDirectoryWrite(DirectoryList::MEDIA)->getAbsolutePath($this->subDir.'/image');
}
}


now in your edit for tab add this in the method _prepareForm right after declaring the fieldset



$fieldset->addType('image', '[Namespace][Module]BlockAdminhtml[Entity]HelperImage');


and add your image field like this



$fieldset->addField(
'image_field_name',
'image',
[
'name' => 'image_field_name',
'label' => __('Image field Label'),
'title' => __('Image field Label'),
]
);


In the controller that saves your entity you need to inject in the constructor the following classes



MagentoMediaStorageModelFileUploaderFactory and [Namespace][Module]Model[Entity]Image



So make your class look like this



<?php
use MagentoFrameworkExceptionLocalizedException as FrameworkException;

class ....

protected $uploaderFactory;
protected $imageModel;

public function __construct(
....
MagentoMediaStorageModelFileUploaderFactory $uploaderFactory,
[Namespace][Module]Model[Entity]Image $imageModel,
....
){
...
$this->uploaderFactory = $uploaderFactory;
$this->imageModel = $imageModel;
...
}


Now, in the same controller add this, before calling $[entity]->save()



$imageName = $this->uploadFileAndGetName('image_field_name', $this->imageModel->getBaseDir(), $data);
$[entity]->setImageFieldName($imageName);


and create this method:



public function uploadFileAndGetName($input, $destinationFolder, $data)
{
try {
if (isset($data[$input]['delete'])) {
return '';
} else {
$uploader = $this->uploaderFactory->create(['fileId' => $input]);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$result = $uploader->save($destinationFolder);
return $result['file'];
}
} catch (Exception $e) {
if ($e->getCode() != MagentoFrameworkFileUploader::TMP_NAME_EMPTY) {
throw new FrameworkException($e->getMessage());
} else {
if (isset($data[$input]['value'])) {
return $data[$input]['value'];
}
}
}
return '';
}


A full example on how to create an entity that supports image and file upload (it's a bit different than described here as it contains an extra class for upload) can be found here







share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 11 '17 at 13:57









Simon

1156




1156










answered Oct 13 '15 at 8:09









MariusMarius

168k28324692




168k28324692













  • given url exension not working. it throw error on screen exception 'MagentoFrameworkExceptionLocalizedException' with message 'Source class "MagentoFrameworkViewElementUiComponentDataProviderCollection" for "MagentoFrameworkViewElementUiComponentDataProviderCollectionFactory" generation does not exist.'

    – Suresh Chikani
    Oct 13 '15 at 8:48











  • @SHPatel. Clear the contents of var/generation. If this problem persists it can for 2 reasons. You either don't have the latest version of Magento 2 or my extension does not work on the latest version. If the problem is my extension I will check it when I have some time.

    – Marius
    Oct 13 '15 at 11:11











  • @Marius, How can we display such image into adminhtml Grid section too? Right now is Default magento 2 is showing it for Product Grid.

    – Praful Rajput
    Oct 13 '15 at 13:29











  • @PrafulRajput. I didn't get to check that part out yet. I have no idea how it's done.

    – Marius
    Oct 13 '15 at 13:38











  • @marius this works in RC 2. One thing you mention adding $fieldset->addType('image', '[Namespace][Module]Adminhtml[Entity]HelperImage'); I am pretty sure you are missing a "Block" callout. [Namespace][Module]BlockAdminhtml[Entity]HelperImage

    – Eirik
    Nov 9 '15 at 20:47



















  • given url exension not working. it throw error on screen exception 'MagentoFrameworkExceptionLocalizedException' with message 'Source class "MagentoFrameworkViewElementUiComponentDataProviderCollection" for "MagentoFrameworkViewElementUiComponentDataProviderCollectionFactory" generation does not exist.'

    – Suresh Chikani
    Oct 13 '15 at 8:48











  • @SHPatel. Clear the contents of var/generation. If this problem persists it can for 2 reasons. You either don't have the latest version of Magento 2 or my extension does not work on the latest version. If the problem is my extension I will check it when I have some time.

    – Marius
    Oct 13 '15 at 11:11











  • @Marius, How can we display such image into adminhtml Grid section too? Right now is Default magento 2 is showing it for Product Grid.

    – Praful Rajput
    Oct 13 '15 at 13:29











  • @PrafulRajput. I didn't get to check that part out yet. I have no idea how it's done.

    – Marius
    Oct 13 '15 at 13:38











  • @marius this works in RC 2. One thing you mention adding $fieldset->addType('image', '[Namespace][Module]Adminhtml[Entity]HelperImage'); I am pretty sure you are missing a "Block" callout. [Namespace][Module]BlockAdminhtml[Entity]HelperImage

    – Eirik
    Nov 9 '15 at 20:47

















given url exension not working. it throw error on screen exception 'MagentoFrameworkExceptionLocalizedException' with message 'Source class "MagentoFrameworkViewElementUiComponentDataProviderCollection" for "MagentoFrameworkViewElementUiComponentDataProviderCollectionFactory" generation does not exist.'

– Suresh Chikani
Oct 13 '15 at 8:48





given url exension not working. it throw error on screen exception 'MagentoFrameworkExceptionLocalizedException' with message 'Source class "MagentoFrameworkViewElementUiComponentDataProviderCollection" for "MagentoFrameworkViewElementUiComponentDataProviderCollectionFactory" generation does not exist.'

– Suresh Chikani
Oct 13 '15 at 8:48













@SHPatel. Clear the contents of var/generation. If this problem persists it can for 2 reasons. You either don't have the latest version of Magento 2 or my extension does not work on the latest version. If the problem is my extension I will check it when I have some time.

– Marius
Oct 13 '15 at 11:11





@SHPatel. Clear the contents of var/generation. If this problem persists it can for 2 reasons. You either don't have the latest version of Magento 2 or my extension does not work on the latest version. If the problem is my extension I will check it when I have some time.

– Marius
Oct 13 '15 at 11:11













@Marius, How can we display such image into adminhtml Grid section too? Right now is Default magento 2 is showing it for Product Grid.

– Praful Rajput
Oct 13 '15 at 13:29





@Marius, How can we display such image into adminhtml Grid section too? Right now is Default magento 2 is showing it for Product Grid.

– Praful Rajput
Oct 13 '15 at 13:29













@PrafulRajput. I didn't get to check that part out yet. I have no idea how it's done.

– Marius
Oct 13 '15 at 13:38





@PrafulRajput. I didn't get to check that part out yet. I have no idea how it's done.

– Marius
Oct 13 '15 at 13:38













@marius this works in RC 2. One thing you mention adding $fieldset->addType('image', '[Namespace][Module]Adminhtml[Entity]HelperImage'); I am pretty sure you are missing a "Block" callout. [Namespace][Module]BlockAdminhtml[Entity]HelperImage

– Eirik
Nov 9 '15 at 20:47





@marius this works in RC 2. One thing you mention adding $fieldset->addType('image', '[Namespace][Module]Adminhtml[Entity]HelperImage'); I am pretty sure you are missing a "Block" callout. [Namespace][Module]BlockAdminhtml[Entity]HelperImage

– Eirik
Nov 9 '15 at 20:47













3














Admin module for basic add update news is here.
In case you are looking for simple image upload solution look at the following snippet which is take from the link.



use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoBackendAppAction;
protected $_fileUploaderFactory;
public function __construct(
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
ActionContext $context
) {
$this->_fileUploaderFactory = $fileUploaderFactory;
parent::__construct($context);
}
public function execute(){
$uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = $this->_objectManager->get('MagentoFrameworkFilesystem')->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath('images/');
$uploader->save($path);
}





share|improve this answer


























  • _filesystem not definded :(

    – fudu
    Oct 30 '18 at 8:48











  • found it, we need to add this to work, also create it in construct() function as well use MagentoFrameworkFilesystem;

    – fudu
    Oct 30 '18 at 8:57











  • Replace _filesystem by $this->_objectManager->get('MagentoFrameworkFilesystem')

    – divya sekar
    30 mins ago
















3














Admin module for basic add update news is here.
In case you are looking for simple image upload solution look at the following snippet which is take from the link.



use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoBackendAppAction;
protected $_fileUploaderFactory;
public function __construct(
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
ActionContext $context
) {
$this->_fileUploaderFactory = $fileUploaderFactory;
parent::__construct($context);
}
public function execute(){
$uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = $this->_objectManager->get('MagentoFrameworkFilesystem')->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath('images/');
$uploader->save($path);
}





share|improve this answer


























  • _filesystem not definded :(

    – fudu
    Oct 30 '18 at 8:48











  • found it, we need to add this to work, also create it in construct() function as well use MagentoFrameworkFilesystem;

    – fudu
    Oct 30 '18 at 8:57











  • Replace _filesystem by $this->_objectManager->get('MagentoFrameworkFilesystem')

    – divya sekar
    30 mins ago














3












3








3







Admin module for basic add update news is here.
In case you are looking for simple image upload solution look at the following snippet which is take from the link.



use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoBackendAppAction;
protected $_fileUploaderFactory;
public function __construct(
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
ActionContext $context
) {
$this->_fileUploaderFactory = $fileUploaderFactory;
parent::__construct($context);
}
public function execute(){
$uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = $this->_objectManager->get('MagentoFrameworkFilesystem')->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath('images/');
$uploader->save($path);
}





share|improve this answer















Admin module for basic add update news is here.
In case you are looking for simple image upload solution look at the following snippet which is take from the link.



use MagentoFrameworkAppFilesystemDirectoryList;
use MagentoBackendAppAction;
protected $_fileUploaderFactory;
public function __construct(
MagentoMediaStorageModelFileUploaderFactory $fileUploaderFactory,
ActionContext $context
) {
$this->_fileUploaderFactory = $fileUploaderFactory;
parent::__construct($context);
}
public function execute(){
$uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = $this->_objectManager->get('MagentoFrameworkFilesystem')->getDirectoryRead(DirectoryList::MEDIA)
->getAbsolutePath('images/');
$uploader->save($path);
}






share|improve this answer














share|improve this answer



share|improve this answer








edited 8 mins ago









divya sekar

32214




32214










answered Jun 5 '16 at 20:02









Imran ZahoorImran Zahoor

26124




26124













  • _filesystem not definded :(

    – fudu
    Oct 30 '18 at 8:48











  • found it, we need to add this to work, also create it in construct() function as well use MagentoFrameworkFilesystem;

    – fudu
    Oct 30 '18 at 8:57











  • Replace _filesystem by $this->_objectManager->get('MagentoFrameworkFilesystem')

    – divya sekar
    30 mins ago



















  • _filesystem not definded :(

    – fudu
    Oct 30 '18 at 8:48











  • found it, we need to add this to work, also create it in construct() function as well use MagentoFrameworkFilesystem;

    – fudu
    Oct 30 '18 at 8:57











  • Replace _filesystem by $this->_objectManager->get('MagentoFrameworkFilesystem')

    – divya sekar
    30 mins ago

















_filesystem not definded :(

– fudu
Oct 30 '18 at 8:48





_filesystem not definded :(

– fudu
Oct 30 '18 at 8:48













found it, we need to add this to work, also create it in construct() function as well use MagentoFrameworkFilesystem;

– fudu
Oct 30 '18 at 8:57





found it, we need to add this to work, also create it in construct() function as well use MagentoFrameworkFilesystem;

– fudu
Oct 30 '18 at 8:57













Replace _filesystem by $this->_objectManager->get('MagentoFrameworkFilesystem')

– divya sekar
30 mins ago





Replace _filesystem by $this->_objectManager->get('MagentoFrameworkFilesystem')

– divya sekar
30 mins ago











1














You could add image field in _prepareForm() method of your admin form:



$fieldset->addField(
'imagefieldname',
'image',
array(
'name' => 'imagefieldname',
'label' => __('Image'),
'title' => __('Image')
)

);





share|improve this answer





















  • 1





    @chanresh image field added done but i need to display image preview on form.

    – Suresh Chikani
    Oct 13 '15 at 8:49






  • 1





    If you upload image and save the record then it will show small thumbnail near "Choose File" input file field.

    – Chandresh P.
    Oct 13 '15 at 9:08








  • 1





    I have uplode image and save it but thumbnail image can't display.

    – Suresh Chikani
    Oct 13 '15 at 9:27











  • Please add your code snippet for _prepareForm().

    – Chandresh P.
    Oct 13 '15 at 12:24











  • check my question, question updated with _prepareForm().

    – Suresh Chikani
    Oct 13 '15 at 12:36
















1














You could add image field in _prepareForm() method of your admin form:



$fieldset->addField(
'imagefieldname',
'image',
array(
'name' => 'imagefieldname',
'label' => __('Image'),
'title' => __('Image')
)

);





share|improve this answer





















  • 1





    @chanresh image field added done but i need to display image preview on form.

    – Suresh Chikani
    Oct 13 '15 at 8:49






  • 1





    If you upload image and save the record then it will show small thumbnail near "Choose File" input file field.

    – Chandresh P.
    Oct 13 '15 at 9:08








  • 1





    I have uplode image and save it but thumbnail image can't display.

    – Suresh Chikani
    Oct 13 '15 at 9:27











  • Please add your code snippet for _prepareForm().

    – Chandresh P.
    Oct 13 '15 at 12:24











  • check my question, question updated with _prepareForm().

    – Suresh Chikani
    Oct 13 '15 at 12:36














1












1








1







You could add image field in _prepareForm() method of your admin form:



$fieldset->addField(
'imagefieldname',
'image',
array(
'name' => 'imagefieldname',
'label' => __('Image'),
'title' => __('Image')
)

);





share|improve this answer















You could add image field in _prepareForm() method of your admin form:



$fieldset->addField(
'imagefieldname',
'image',
array(
'name' => 'imagefieldname',
'label' => __('Image'),
'title' => __('Image')
)

);






share|improve this answer














share|improve this answer



share|improve this answer








edited Dec 8 '16 at 6:11









Qaisar Satti

27.1k1256109




27.1k1256109










answered Oct 13 '15 at 7:39









Chandresh P.Chandresh P.

336214




336214








  • 1





    @chanresh image field added done but i need to display image preview on form.

    – Suresh Chikani
    Oct 13 '15 at 8:49






  • 1





    If you upload image and save the record then it will show small thumbnail near "Choose File" input file field.

    – Chandresh P.
    Oct 13 '15 at 9:08








  • 1





    I have uplode image and save it but thumbnail image can't display.

    – Suresh Chikani
    Oct 13 '15 at 9:27











  • Please add your code snippet for _prepareForm().

    – Chandresh P.
    Oct 13 '15 at 12:24











  • check my question, question updated with _prepareForm().

    – Suresh Chikani
    Oct 13 '15 at 12:36














  • 1





    @chanresh image field added done but i need to display image preview on form.

    – Suresh Chikani
    Oct 13 '15 at 8:49






  • 1





    If you upload image and save the record then it will show small thumbnail near "Choose File" input file field.

    – Chandresh P.
    Oct 13 '15 at 9:08








  • 1





    I have uplode image and save it but thumbnail image can't display.

    – Suresh Chikani
    Oct 13 '15 at 9:27











  • Please add your code snippet for _prepareForm().

    – Chandresh P.
    Oct 13 '15 at 12:24











  • check my question, question updated with _prepareForm().

    – Suresh Chikani
    Oct 13 '15 at 12:36








1




1





@chanresh image field added done but i need to display image preview on form.

– Suresh Chikani
Oct 13 '15 at 8:49





@chanresh image field added done but i need to display image preview on form.

– Suresh Chikani
Oct 13 '15 at 8:49




1




1





If you upload image and save the record then it will show small thumbnail near "Choose File" input file field.

– Chandresh P.
Oct 13 '15 at 9:08







If you upload image and save the record then it will show small thumbnail near "Choose File" input file field.

– Chandresh P.
Oct 13 '15 at 9:08






1




1





I have uplode image and save it but thumbnail image can't display.

– Suresh Chikani
Oct 13 '15 at 9:27





I have uplode image and save it but thumbnail image can't display.

– Suresh Chikani
Oct 13 '15 at 9:27













Please add your code snippet for _prepareForm().

– Chandresh P.
Oct 13 '15 at 12:24





Please add your code snippet for _prepareForm().

– Chandresh P.
Oct 13 '15 at 12:24













check my question, question updated with _prepareForm().

– Suresh Chikani
Oct 13 '15 at 12:36





check my question, question updated with _prepareForm().

– Suresh Chikani
Oct 13 '15 at 12:36


















draft saved

draft discarded




















































Thanks for contributing an answer to Magento Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f86125%2fmagento2-admin-module-image-upload-code-to-display-form%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

What other Star Trek series did the main TNG cast show up in?

Berlina muro

Berlina aerponto