Magento2 Image Upload with Delete checkbox and Render Image in Grid

Admin Form File Of Module


<?php
namespace Namespace\ModuleName\Block\Adminhtml\Model\Edit\Tab;
class Main extends \Magento\Backend\Block\Widget\Form\Generic implements \Magento\Backend\Block\Widget\Tab\TabInterface
{
    /**
     * @var \Magento\Store\Model\System\Store
     */
    protected $_systemStore;
     protected $_allowedAttribute;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magento\Framework\Data\FormFactory $formFactory
     * @param \Magento\Store\Model\System\Store $systemStore
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\Data\FormFactory $formFactory,
         \Namespace\ModuleName\Model\System\Config\Status $allowedAttribute,
        \Magento\Store\Model\System\Store $systemStore,
        array $data = array()
    ) {
        $this->_systemStore = $systemStore;
        $this->_allowedAttribute = $allowedAttribute;
        parent::__construct($context, $registry, $formFactory, $data);
    }

    /**
     * Prepare form
     *
     * @return $this
     */
    protected function _prepareForm()
    {
  /* @var $model \Magento\Cms\Model\Page */
        $model = $this->_coreRegistry->registry('ModuleName_model');
  $isElementDisabled = false;
        /** @var \Magento\Framework\Data\Form $form */
        $form = $this->_formFactory->create();

        $form->setHtmlIdPrefix('page_');

        $fieldset = $form->addFieldset('base_fieldset', array('legend' => __('Main')));
        
        /*$fieldset->addType('image', '\Namespace\ModuleName\Block\Adminhtml\Model\Grid\Renderer\Image1');*/

        if ($model->getId()) {
            $fieldset->addField('id', 'hidden', array('name' => 'id'));
        } 


     $fieldset->addField(
    'status',
    'select',
    [    'name' =>'status',
        'label' => __('Status'),
        'title' => __('Enable/Disable'),
        'required' => true,
        'options' => ['1' => __('Enable'), '0' => __('Disable')]
    ]
        );


         $fieldset->addField(
            'country',
            'select',
            array(
                'name' => 'country',
                'label' => __('Select Country'),
                'title' => __('Select Country'),
                'values' => $this->_allowedAttribute->toOptionArray(),
                /*'required' => true,*/
            )
        );
 
        $fieldset->addField(
            'storeimage',
            'image',
            array(
                'name' => 'storeimage',
                'label' => __('Store Image'),
                'title' => __('Store Image'),
                /*'required' => true,*/
                'note' => 'Allow image type: jpg, jpeg, gif, png',
            )
        );



 
  /*{{CedAddFormField}}*/
        
        if (!$model->getId()) {
            $model->setData('status', $isElementDisabled ? '2' : '1');
        }

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

        return parent::_prepareForm();   
    }

    /**
     * Prepare label for tab
     *
     * @return string
     */
    public function getTabLabel()
    {
        return __('Main');
    }

    /**
     * Prepare title for tab
     *
     * @return string
     */
    public function getTabTitle()
    {
        return __('Main');
    }

    /**
     * {@inheritdoc}
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isHidden()
    {
        return false;
    }

    /**
     * Check permission for passed action
     *
     * @param string $resourceId
     * @return bool
     */
    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }
}

Create a file inside    

Namespace=>ModuleName=>Block=>Adminhtml=>ModelGrid==>>Renderer  with name Image1




<?php
namespace Namespace\ModuleName\Block\Adminhtml\Model\Grid\Renderer;



class Image1 extends  \Magento\Framework\Data\Form\Element\Image
{
    /**
     * Post image model
     *
     * @var \Mageplaza\Blog\Model\Post\Image
     */
    public $imageModel;

    /**
     * constructor
     *
     * @param \Mageplaza\Blog\Model\Post\Image $imageModel
     * @param \Magento\Framework\Data\Form\Element\Factory $factoryElement
     * @param \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection
     * @param \Magento\Framework\Escaper $escaper
     * @param \Magento\Framework\UrlInterface $urlBuilder
     * @param array $data
     */
    public function __construct(
        \Namespace\ModuleName\Model\System\Config\Image $imageModel,
        \Magento\Framework\Data\Form\Element\Factory $factoryElement,
        \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection,
        \Magento\Framework\Escaper $escaper,
        \Magento\Framework\UrlInterface $urlBuilder,
        array $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;
    }
}

Create a file inside  

  Namespace=>ModuleName=>Model==>>System==>>Config with name  Image 


<?php

namespace Namespace\ModuleName\Model\System\Config;


/**
 * Class Config
 *
 * @package Name\MyModule\Model\Config\Backend
 */
class Image 
{
    /**
     * Media sub folder
     *
     * @var string
     */
    public $subDir = 'bluethink';

    /**
     * URL builder
     *
     * @var \Magento\Framework\UrlInterface
     */
    public $urlBuilder;

    /**
     * File system model
     *
     * @var \Magento\Framework\Filesystem
     */
    public $fileSystem;

    /**
     * constructor
     *
     * @param \Magento\Framework\UrlInterface $urlBuilder
     * @param \Magento\Framework\Filesystem $fileSystem
     */
    public function __construct(
        \Magento\Framework\UrlInterface $urlBuilder,
        \Magento\Framework\Filesystem $fileSystem
    ) {
    
        $this->urlBuilder = $urlBuilder;
        $this->fileSystem = $fileSystem;
    }

    /**
     * get images base url
     *
     * @return string
     */
    public function getBaseUrl()
    {
        return $this->urlBuilder->getBaseUrl(['_type' => \Magento\Framework\UrlInterface::URL_TYPE_MEDIA])
            .$this->subDir.'/storeimage';
    }
    /**
     * get base image dir
     *
     * @return string
     */
    public function getBaseDir()
    {
        return $this->fileSystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)
            ->getAbsolutePath($this->subDir.'/storeimage');
    }
}


To Render Image in Grid

<?php
namespace Namespace\ModuleName\Block\Adminhtml\Model\Grid\Renderer;

use Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer;
use Magento\Framework\DataObject;
use Magento\Store\Model\StoreManagerInterface;

class Image extends AbstractRenderer
{
    private $_storeManager;
    /**
     * @param \Magento\Backend\Block\Context $context
     * @param array $data
     */
    public function __construct(\Magento\Backend\Block\Context $context, StoreManagerInterface $storemanager, array $data = [])
    {
        $this->_storeManager = $storemanager;
        parent::__construct($context, $data);
        $this->_authorization = $context->getAuthorization();
    }
    /**
     * Renders grid column
     *
     * @param Object $row
     * @return  string
     */
    public function render(DataObject $row)
    {
   
         $mediaDirectory = $this->_storeManager->getStore()->getBaseUrl(
            \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
        );
       
         $imageUrl = $mediaDirectory.'Namespace/storeimage'.$this->_getValue($row); 
         path 
        return '<img src="'.$imageUrl.'" width="70"/>';


        
    }
}

Add this in Grid.php

<?php
$this->addColumn(
            'storeimage',
            [
                'header' => __('storeimage'),
                'index' => 'storeimage',
                'class' => 'storeimage',
                'renderer'  => '\Bluethink\Storelocator\Block\Adminhtml\Model\Grid\Renderer\Image'
            ]
        );
?>

Comments

Popular posts from this blog

Through Postman Api send data through JSON and create simple product in Magento2

Getting product Image in PHTML in Magento2

programmaticlly Create Order in Magento2 with custom options in order