0

Hello everyone in my case I want to add an image field in a custom form inside a custom module I have already the crud worked fine with the other fields like file_id,name,created_at updated_at, but I don't know how to add the field 'logo', and what files I have to change.

if anyone can help me please I will be appreciated ?

1
  • Please check and update me.
    – Msquare
    Nov 19 '20 at 10:12
1

Add new column into InstallSchema.php for image

->addColumn(
            'img',
            \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
            255,
            ['nullable' => true],
            'Image'
        )

Add Form type must be this

enctype="multipart/form-data" : No characters are encoded. This value is required when you are using forms that have a file upload control.

$form = $this->_formFactory->create(
    ['data' => [
                    'id' => 'edit_form',
                    'enctype' => 'multipart/form-data',
                    'action' => $this->getData('action'),
                    'method' => 'post'
                ]
    ]
);  

Add field into your form

$fieldset->addField(
        'img',
        'image', 
        [
            'name' => 'img',
            'label' => __('Upload Image'),
            'title' => __('Upload Image'),
            'required' => true,
            'note' => 'Allow image type: jpg, jpeg, png',
            'class' => 'required-entry required-file',
        ]
    );

For Save Image

    protected $fileSystem;

    protected $uploaderFactory;

    protected $adapterFactory;


    public function __construct(
        .............................................
        \Magento\Framework\Filesystem $fileSystem,
        \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
        \Magento\Framework\Image\AdapterFactory $adapterFactory,
        .............................................
    ) {
        .............................................
        $this->fileSystem = $fileSystem;
        $this->adapterFactory = $adapterFactory;
        $this->uploaderFactory = $uploaderFactory;
        .............................................
    }

    public function execute()
    {
        $data = $this->getRequest()->getPostValue();

        /* for delete image */

        if (isset($data['img']['delete'])) {
            if ($data['img']['delete'] == 1) {
                $data['img'] = '';
            }
        }

        /* for upload image */
        if ((isset($_FILES['img']['name'])) && ($_FILES['img']['name'] != '') && (!isset($data['img']['delete']))) {
            try
            {
                $uploaderFactory = $this->uploaderFactory->create(['fileId' => 'img']);
                $uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                $imageAdapter = $this->adapterFactory->create();
                $uploaderFactory->setAllowRenameFiles(true);
                $uploaderFactory->setFilesDispersion(true);
                $mediaDirectory = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA);
                $destinationPath = $mediaDirectory->getAbsolutePath('Vendorename_ModuleName_IMG');

                //echo "<br/>destination path".$destinationPath;

                $result = $uploaderFactory->save($destinationPath);

                // print_r($result);

                if (!$result) {
                    throw new LocalizedException
                        (
                        __('File cannot be saved to path: $1', $destinationPath)
                    );

                }

                $imagePath = 'Vendorename_ModuleName_IMG' . $result['file'];

                //echo "<br/> Image store ".$imagePath;

                $data['img'] = $imagePath;


            } // try block
             catch (\Exception $e) {
                $this->messageManager->addError(__("Image not Upload Pleae Try Again"));
            }

        }

        .............................................
        .............................................

        echo "<pre>";
        print_r($data)
        exit();

  }
}

For show image into Grid

    <column name="img" class="Vendorename\Modulename\Ui\Component\Listing\Column\Thumbnail">
       <argument name="data" xsi:type="array">
           <item name="config" xsi:type="array">
               <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/thumbnail</item>
                   <item name="sortable" xsi:type="boolean">false</item>
                   <item name="altField" xsi:type="string">store image</item>
                   <item name="has_preview" xsi:type="string">1</item>
              <item name="filter" xsi:type="string">text</item>
              <item name="label" xsi:type="string" translate="true">Image</item>
              <item name="sortOrder" xsi:type="number">80</item>
           </item>
       </argument>
   </column>

Vendorename\Modulename\Ui\Component\Listing\Column

Thumbnail.php

<?php
namespace Vendorename\Modulename\Ui\Component\Listing\Column;

use Magento\Catalog\Helper\Image;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Ui\Component\Listing\Columns\Column;

class Thumbnail extends Column
{
    const ALT_FIELD = 'title';

    protected $storeManager;

    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        Image $imageHelper,
        UrlInterface $urlBuilder,
        StoreManagerInterface $storeManager,
        array $components = [],
        array $data = []
    ) {
        $this->storeManager = $storeManager;
        $this->imageHelper = $imageHelper;
        $this->urlBuilder = $urlBuilder;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepareDataSource(array $dataSource)
    {
        if(isset($dataSource['data']['items'])) {
            $fieldName = $this->getData('name');
            foreach($dataSource['data']['items'] as & $item) {
                $url = '';
                if($item[$fieldName] != '') {
                    $url = $this->storeManager->getStore()->getBaseUrl(
                        \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
                    ).$item[$fieldName];
                }
                $item[$fieldName . '_src'] = $url;
                $item[$fieldName . '_alt'] = $this->getAlt($item) ?: '';
                $item[$fieldName . '_link'] = $this->urlBuilder->getUrl('routename/controllername/actionname',['id' => $item['id']]);
                $item[$fieldName . '_orig_src'] = $url;
            }
        }

        return $dataSource;
    }

    protected function getAlt($row)
    {
        $altField = $this->getData('config/altField') ?: self::ALT_FIELD;
        return isset($row[$altField]) ? $row[$altField] : null;
    }
}

Run Magento command

php bin/magento s:up
php bin/magento c:c

I Hope This Helps You.

3
  • thank you for your response it worked like the charm, but not for the delete option
    – coding mv
    Nov 19 '20 at 14:39
  • and what link should i ut here , is for ndex or edit $item[$fieldName . '_link'] = $this->urlBuilder->getUrl('myroute/items/index',['id' => $item['id']]);
    – coding mv
    Nov 19 '20 at 14:57
  • also when i click on the save button when i edit the item , it add a new identical item from the one which i was edited , have you any ideas please ?
    – coding mv
    Nov 19 '20 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.