I have admin form in which I have image upload option, everything is working fine, but I am not able to figure out, how to display preview of uploaded image.
It will be great help if someone can help me with this. thanks
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI have admin form in which I have image upload option, everything is working fine, but I am not able to figure out, how to display preview of uploaded image.
It will be great help if someone can help me with this. thanks
Namespace: Book
ModuleName: Flip
Add addType() in admin form
$fieldset->addType(
'image',
'\Book\Flip\Block\Adminhtml\Flip\Renderer\Image'
);
Now create renderer block(Image.php) at
Book\Flip\Block\Adminhtml\Flip\Renderer
Copy this code
<?php
namespace Book\Flip\Block\Adminhtml\Flip\Renderer;
class Image extends \Magento\Framework\Data\Form\Element\Image
{
protected function _getUrl()
{
$url = 'book'.$this->getValue(); // book is image directory
return $url;
}
}
Now you can see image on admin form.
You can set Renderer in form php file..like as
$fieldset->addType(
'image',
'\Test\ModuleName\Block\Adminhtml\Testing\Form\Renderer\Image'
);
Image.php file like as
<?php
namespace Test\ModuleName\Block\Adminhtml\Testing\Form\Renderer;
use Magento\Framework\Data\Form\Element\Image as ImageField;
use Magento\Framework\Data\Form\Element\Factory as ElementFactory;
use Magento\Framework\Data\Form\Element\CollectionFactory as ElementCollectionFactory;
use Magento\Framework\Escaper;
use Test\ModuleName\Helper\Data as TestImage;
use Magento\Framework\UrlInterface;
class Customfield extends ImageField
{
protected $_imageModel;
public function __construct(
TestImage $imageModel,
ElementFactory $factoryElement,
ElementCollectionFactory $factoryCollection,
Escaper $escaper,
UrlInterface $urlBuilder,
$data = []
) {
$this->_imageModel = $imageModel;
parent::__construct(
$factoryElement, $factoryCollection, $escaper, $urlBuilder, $data
);
}
protected function _getUrl()
{
$url = false;
if ($this->getValue()) {
$url = $this->_imageModel
->getBaseUrlMedia() . 'foldername/' . $this->getValue();
}
return $url;
}
}
Follow given below URL or use given below code to solve the issue. URL: magento 2 : Display Uploaded image in admin form custom module
Custom code to be implemented
Step1: Add addType() in admin form(Edit/Tab/Main.php)
// From where your form code is coming
$fieldset->addField(
'image',
'image',
[
'name' => 'image',
'label' => __('Image'),
'title' => __('Image'),
'required' => false,
'disabled' => $isElementDisabled
]
);
Step2: In Grid.php
paste this code
$this->addColumn(
'image2wbmp(image)',
[
'header' => __('Image'),
'align' => 'center',
'index' => 'image',
'renderer' => '\Book\Flip\Block\Adminhtml\Flip\Grid\Renderer\Image',
]
);
Step3: Now create renderer block(Image.php)
at app\code\Book\Flip\Block\Adminhtml\Flip\Grid\Renderer adn paste this code