2

How to add image uploader as like in the category?

4 Answers 4

3

Reference Link : Click Here

Follow this below steps to add image uploader in ui form :

1) Add this below code in your form's xml file :

<field name="review_image">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="dataType" xsi:type="string">string</item>
            <item name="label" xsi:type="string" translate="true">Image</item>
            <item name="visible" xsi:type="boolean">true</item>
            <item name="formElement" xsi:type="string">fileUploader</item>
            <item name="elementTmpl" xsi:type="string">ui/form/element/uploader/uploader</item>
            <item name="previewTmpl" xsi:type="string">Magento_Catalog/image-preview</item>
            <item name="required" xsi:type="boolean">true</item>
            <item name="validation" xsi:type="array">
                <item name="required-entry" xsi:type="boolean">true</item>
            </item>
            <item name="uploaderConfig" xsi:type="array">
                <item name="url" xsi:type="url" path="vendor_module/index/upload"/>
            </item>
        </item>
    </argument>
</field>

2) Now, you need to create virtualType of Image uploader in di.xml file. Add this below code in your di.xml file :

<!-- Image Uploader -->
<virtualType name="VirtualTypeName" type="Magento\Catalog\Model\ImageUploader">
    <arguments>
        <argument name="baseTmpPath" xsi:type="string">productreview/tmp/image</argument>
        <argument name="basePath" xsi:type="string">productreview/image</argument>
        <argument name="allowedExtensions" xsi:type="array">
            <item name="jpg" xsi:type="string">jpg</item>
            <item name="jpeg" xsi:type="string">jpeg</item>
            <item name="gif" xsi:type="string">gif</item>
            <item name="png" xsi:type="string">png</item>
        </argument>
    </arguments>
</virtualType>
<type name="VendorName\ModuleName\Controller\Adminhtml\Index\Upload">
    <arguments>
        <argument name="imageUploader" xsi:type="object">VirtualTypeName</argument>
    </arguments>
</type>
<!-- End Image Uploader -->

3) Now, create controller upload.php and add this below code :

<?php

namespace VendorName\ModuleName\Controller\Adminhtml\Index;

use Magento\Framework\Controller\ResultFactory;

class Upload extends \Magento\Backend\App\Action {
    /**
     * Image uploader
     *
     * @var \Magento\Catalog\Model\ImageUploader
     */
    protected $imageUploader;

    /**
     * Upload constructor.
     *
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Catalog\Model\ImageUploader $imageUploader
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Catalog\Model\ImageUploader $imageUploader
    ) {
        parent::__construct($context);
        $this->imageUploader = $imageUploader;
    }

    /**
     * Upload file controller action.
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute() {
        $imageUploadId = $this->_request->getParam('param_name', 'review_image');
        try {
            $imageResult = $this->imageUploader->saveFileToTmpDir($imageUploadId);

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

4) Then, you need to add js file in requirejs-config.js file. Add this below code in your requirejs-config.js file :

/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

var config = {
    map: {
        '*': {
            'Magento_Ui/js/form/element/file-uploader': 'VendorName_ModuleName/js/form/element/file-uploader'
        }
    }
};

5) Then, copy js file from /vendor/magento/module-ui/view/base/web/js/form/element/file-uploader.js and add into VendorName_ModuleName/js/form/element/file-uploader folder.

Refresh it and check it.

1
  • where to define the image directory path?
    – jojo
    Mar 30, 2020 at 2:39
0

\Vendor\ComputerGames\Controller\Adminhtml\Game\Edit

<?php

declare(strict_types=1);
namespace Vendor\ComputerGames\Controller\Adminhtml\Game;

use Magento\Backend\App\Action;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;

/**
 * Edit the page
 *
 * Class Edit
 */
class Edit extends Action
{
    /**
     * @var PageFactory
     */
    protected PageFactory $resultPageFactory;
    /**
     * @var Registry
     */
    protected Registry $coreRegistry;

    /**
     * @param PageFactory $resultPageFactory
     * @param Registry $coreRegistry
     * @param Action\Context $context
     */
    public function __construct(
        PageFactory $resultPageFactory,
        Registry $coreRegistry,
        Action\Context $context
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->coreRegistry = $coreRegistry;
        parent::__construct($context);
    }

    /**
     * Edit the record through regisstry
     *
     * @return ResultInterface|Page
     */
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->prepend(__('Edit Game'));
        $gameId = $this->getRequest()->getParam('game_id');
        $this->coreRegistry->register('game_id', $gameId);
        return $resultPage;
    }
    /**
     * _isAllowed
     *
     * @return void
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Moazzam_ComputerGames::grid');
    }
}

Vendor/ComputerGames/view/adminhtml/web/template/image-preview.html

image preview fix during update the image

<div class="file-uploader-summary">
    <div class="file-uploader-preview">
        <a attr="href: $parent.getFilePreview($file)" target="_blank">
            <img
                alt="Thumbnail Image"
                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>
0

in forms.xml where path="vendor_module/index/upload" instead "vendor_module" we have to past our "admin_rote"

0

computer_games_form.xml

<?xml version="1.0" encoding="UTF-8"?>

<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider"
                  xsi:type="string">computer_games_form.game_form_data_source</item>
        </item>
        <item name="label" xsi:type="string" translate="true">Computer Game
            Information</item>
        <item name="template" xsi:type="string">templates/form/collapsible</item>
    </argument>
    <settings>
        <buttons>
            <button name="save"
                    class="Vendor\ComputerGames\Block\Adminhtml\Edit\Button\Save"/>
            <button name="delete"
                    class="Vendor\ComputerGames\Block\Adminhtml\Edit\Button\Delete"/>
            <button name="back"
                    class="Vendor\ComputerGames\Block\Adminhtml\Edit\Button\Back"/>
            <button name="save_and_continue"
                    class="Vendor\ComputerGames\Block\Adminhtml\Edit\Button\SaveAndContinueButton"/>
        </buttons>
        <namespace>computer_games_form</namespace>
        <dataScope>data</dataScope>
        <deps>
            <dep>computer_games_form.game_form_data_source</dep>
        </deps>
    </settings>
    <dataSource name="game_form_data_source">
        <argument name="data" xsi:type="array">
            <item name="js_config" xsi:type="array">
                <item name="component"
                      xsi:type="string">Magento_Ui/js/form/provider</item>
            </item>
        </argument>
        <settings>
            <submitUrl path="games/game/save"/>
        </settings>
        <dataProvider class="Moazzam\ComputerGames\Model\Game\DataProvider"
                      name="game_form_data_source">
            <settings>
                <requestFieldName>game_id</requestFieldName>
                <primaryFieldName>game_id</primaryFieldName>
            </settings>
        </dataProvider>
    </dataSource>
    <fieldset name="general">
        <settings>
            <componentType>fieldset</componentType>
            <label translate="true">Information</label>
        </settings>
        <field name="game_id" formElement="input">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">computer_games</item>
                </item>
            </argument>
            <settings>
                <dataType>text</dataType>
                <visible>false</visible>
                <dataScope>game_id</dataScope>
            </settings>
        </field>
        <field name="name" sortOrder="20" formElement="input">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">computer_games</item>
                </item>
            </argument>
            <settings>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">true</rule>
                </validation>
                <dataType>text</dataType>
                <label translate="true">Name</label>
                <dataScope>name</dataScope>
            </settings>
        </field>
        <field name="type" formElement="select">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">computer_games</item>
                </item>
            </argument>
            <settings>
                <dataType>number</dataType>
                <label translate="true">Type</label>
                <dataScope>type</dataScope>
            </settings>
            <formElements>
                <select>
                    <settings>
                        <options
                            class="Vendor\ComputerGames\Ui\Component\Options\Types"/>
                    </settings>
                </select>
            </formElements>
        </field>
        <field name="trial_period" formElement="select">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">computer_games</item>
                </item>
            </argument>
            <settings>
                <dataType>number</dataType>
                <label translate="true">Trial Period</label>
                <dataScope>trial_period</dataScope>
            </settings>
            <formElements>
                <select>
                    <settings>
                        <options
                            class="Vendor\ComputerGames\Ui\Component\Options\TrialPeriods"/>
                    </settings>
                </select>
            </formElements>
        </field>
        <field name="image" formElement="imageUploader">
            <settings>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">true</rule>
                </validation>
                <notice translate="true">Allowed file types: jpeg, gif, png.</notice>
                <label translate="true">Image</label>
                <componentType>imageUploader</componentType>
            </settings>
            <formElements>
                <imageUploader>
                    <settings>
                        <maxFileSize>2097152</maxFileSize>
                        <uploaderConfig>
                            <param xsi:type="string"
                                   name="url">games/game_fileUploader/save</param>
                        </uploaderConfig>
                    </settings>
                </imageUploader>
            </formElements>
        </field>
        <field name="release_date" formElement="date">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">computer_games</item>
                </item>
            </argument>
            <settings>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">true</rule>
                    <rule name="validate-date" xsi:type="boolean">true</rule>
                </validation>
                <dataType>text</dataType>
                <label translate="true">Release Date</label>
                <dataScope>release_date</dataScope>
            </settings>
        </field>
    </fieldset>
</form>

Controller

    <?php

declare(strict_types=1);
namespace Vendor\ComputerGames\Controller\Adminhtml\Game;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Catalog\Model\ImageUploader;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\AlreadyExistsException as AlreadyExistsExceptionAlias;
use Vendor\ComputerGames\Model\GameFactory;
use Vendor\ComputerGames\Model\ResourceModel\Game as GameResourceModel;

/**
 * Save the data
 *
 * Class Save
 */
class Save extends Action implements HttpPostActionInterface
{
    /**
     * @var ImageUploader
     */
    protected ImageUploader $imageUploader;

    /**
     * @var GameFactory
     */
    protected GameFactory $gameFactory;

    /**
     * @var GameResourceModel
     */
    protected GameResourceModel $gameResourceModel;
    private Context $context;

    /**
     * @param GameResourceModel $gameResourceModel
     * @param GameFactory $gameFactory
     * @param ImageUploader $imageUploader
     * @param Context $context
     */
    public function __construct(
        GameResourceModel $gameResourceModel,
        GameFactory $gameFactory,
        ImageUploader $imageUploader,
        Context $context
    ) {
        parent::__construct($context);
        $this->imageUploader=$imageUploader;
        $this->gameFactory = $gameFactory;
        $this->gameResourceModel = $gameResourceModel;
        $this->context = $context;
    }

    /**
     * @return ResultInterface
     * @throws AlreadyExistsExceptionAlias
     */
    public function execute(): ResultInterface
    {
        $postData = $this->getRequest()->getParams();
        $model = $this->gameFactory->create();
        if ($postData['game_id']) {
            $this->gameResourceModel->load($model, $postData['game_id']);
        } else {
            unset($postData['game_id']);
        }
        $model->setData($postData);
        if (isset($postData['image'])) {
            try {
                $bannerImage = $postData['image'][0];
                if (strpos($bannerImage['url'], 'computer/image') !== false) {
                    if (isset($bannerImage['file']) && !empty($bannerImage['file'])) {
                        $image = (string)$postData['image'][0]['name'];
                        $imageName = $this->imageUploader->moveFileFromTmp($image);
                        $model->setData('image', $imageName);
                    } else {
                        $imageName = (explode("/", $bannerImage['url']));
                        $model->setData('image', $imageName[6]);
                    }
                } else {
                    $imageName = (explode("/", $bannerImage['url']));
                    $model->setData('image', $imageName[6]);
                }
            } catch (\Exception $e) {
                $imageName = ['error' => $e->getMessage(), 'errorcode' => $e->getCode()];
            }
        }
        $this->gameResourceModel->save($model);
        $this->messageManager->addSuccessMessage('Game Form has been saved');
        $result = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        $result->setPath('games/game/index');
        return $result;
    }
}

dbschema.xml

<?xml version="1.0"?>


<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="computer_games" engine="innodb" comment="Computer games table" resource="default">
        <column xsi:type="int" name="game_id" padding="10" unsigned="true" nullable="false" identity="true" comment="Primary" />
        <column xsi:type="varchar" name="name" nullable="false" comment="Name" />
        <column xsi:type="varchar" name="type" nullable="false" comment="Game type: RPG, Simulator, Shooter, RTS, MMO" />
        <column xsi:type="varchar" name="trial_period"  nullable="false" comment="Trial period" />
        <column xsi:type="varchar" name="image" nullable="false" comment="Game Image" />
        <column xsi:type="date" name="release_date" nullable="false" comment="Release date" />
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="game_id" />
        </constraint>
    </table>
</schema>

\Vendor\ComputerGames\Controller\Adminhtml\Game\FileUploader\Save

<?php

declare(strict_types=1);
namespace Vendor\ComputerGames\Controller\Adminhtml\Game\FileUploader;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Catalog\Model\ImageUploader;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface as ResultInterfaceAlias;

/**
 * Upload the images of games
 *
 * Class Save
 */
class Save extends Action implements HttpPostActionInterface
{
    /**
     * @var ImageUploader
     */
    protected ImageUploader $imageUploader;

    /**
     * @param ImageUploader $imageUploader
     * @param Context $context
     */
    public function __construct(ImageUploader $imageUploader, Context $context)
    {
        parent::__construct($context);
        $this->imageUploader=$imageUploader;
    }

    /**
     * Allow
     *
     * @return bool
     */
    protected function _isAllowed(): bool
    {
        return true;
    }

    /**
     * Save the games images through helper
     *
     * @return ResponseInterface|ResultInterfaceAlias
     */
    public function execute()
    {
        try {
            $result = $this->imageUploader->saveFileToTmpDir('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);
    }
}

\Vendor\ComputerGames\Model\Game\DataProvider

<?php

namespace Vendor\ComputerGames\Model\Game;

use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Ui\DataProvider\AbstractDataProvider as AbstractDataProvider;
use Vendor\ComputerGames\Model\ResourceModel\Game\Collection;
use Vendor\ComputerGames\Model\ResourceModel\Game\CollectionFactory;

/**
 * PLEASE ENTER ONE LINE SHORT DESCRIPTION OF CLASS
 *
 * Class DataProvider
 */
class DataProvider extends AbstractDataProvider
{
    /**
     * @var Collection
     */
    protected $collection;

    /**
     * @var array
     */
    protected array $loadedData;

    protected $storeManger;

    /**
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param CollectionFactory $gameCollectionFactory
     * @param array $meta
     * @param array $data
     */
    public function __construct(
        $name,
        StoreManagerInterface $storeManager,
        $primaryFieldName,
        $requestFieldName,
        CollectionFactory $gameCollectionFactory,
        array $meta = [],
        array $data = []
    ) {
        $this->collection = $gameCollectionFactory->create();
        $this->storeManger=$storeManager;
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
    }

    /**
     * Get data
     *
     * @return array
     */
    public function getData(): array
    {
        $baseurl =  $this->storeManger->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
        $this->loadedData = [];
        if (!empty($this->loadedData)) {
            return $this->loadedData;
        }
        $items = $this->collection->getItems();
        foreach ($items as $game) {
            $temp = $game->getData();
            $img = [];
            $img[0]['name'] = $temp['image'];
            $img[0]['url'] = $baseurl . 'computer/image/' . $temp['image'];
            $temp['image'] = $img;
            $this->loadedData[$game->getId()] = array_merge($game->getData(), $temp);
        }
        return $this->loadedData;
    }
}

app/code/Vendor/ComputerGames/view/adminhtml/ui_component/computer_games_listing.xml

    <?xml version="1.0" encoding="UTF-8"?>

<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd ">
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="provider" xsi:type="string">computer_games_listing.computer_games_listing_data_source</item>
        </item>
    </argument>
    <settings>
        <buttons>
            <button name="add">
                <url path="*/game/edit" />
                <class>primary</class>
                <label translate="true">Add New Game</label>
                <aclResource>Magento_Sales::create</aclResource>
            </button>
        </buttons>
        <spinner>computer_games_columns</spinner>
        <deps>
            <dep>computer_games_listing.computer_games_listing_data_source</dep>
        </deps>
    </settings>
    <dataSource name="computer_games_listing_data_source" component="Magento_Ui/js/grid/provider">
        <settings>
            <updateUrl path="mui/index/render" />
        </settings>
        <aclResource>Vendor_ComputerGames::grid</aclResource>
        <dataProvider class="ComputerGamesGridDataProvider" name="computer_games_listing_data_source">
            <settings>
                <requestFieldName>id</requestFieldName>
                <primaryFieldName>main_table.game_id</primaryFieldName>
            </settings>
        </dataProvider>
    </dataSource>
    <listingToolbar name="listing_top">
        <settings>
            <sticky>true</sticky>
        </settings>
        <bookmark name="bookmarks" />
        <columnsControls name="columns_controls" />
        <exportButton name="export_button" />
        <filterSearch name="fulltext" />
        <filters name="listing_filters" />
        <paging name="listing_paging" />
    </listingToolbar>
    <columns name="computer_games_columns">
        <settings>
            <childDefaults>
                <param name="fieldAction" xsi:type="array">
                    <item name="provider" xsi:type="string">
                        computer_games_listing.computer_games_listing.computer_games_column
                        s.actions</item>
                    <item name="target" xsi:type="string">applyAction</item>
                    <item name="params" xsi:type="array">
                        <item name="0" xsi:type="string">view</item>
                        <item name="1" xsi:type="string">${ $.$data.rowIndex }</item>
                    </item>
                </param>
            </childDefaults>
        </settings>
        <column name="game_id" sortOrder="10">
            <settings>
                <filter>textRange</filter>
                <label translate="true">ID</label>
                <sorting>asc</sorting>
            </settings>
        </column>
        <column name="name">
            <settings>
                <filter>text</filter>
                <label translate="true">Name</label>
            </settings>
        </column>
        <column name="type" component="Magento_Ui/js/grid/columns/select">
            <settings>
                <options class="Vendor\ComputerGames\Ui\Component\Options\Types" />
                <filter>select</filter>
                <dataType>select</dataType>
                <label translate="true">Type</label>
            </settings>
        </column>
        <column name="trial_period">
            <settings>
                <options class="Vendor\ComputerGames\Ui\Component\Options\TrialPeriods" />
                <filter>select</filter>
                <dataType>select</dataType>
                <label translate="true">Trial Period</label>
            </settings>
        </column>
        <column name="release_date" class="Magento\Ui\Component\Listing\Columns\Date"
                component="Magento_Ui/js/grid/columns/date">
            <settings>
                <filter>dateRange</filter>
                <dataType>date</dataType>
                <label translate="true">Release Date</label>
                <sorting>desc</sorting>
                <visible>false</visible>
            </settings>
        </column>
        <column name="image" class="Vendor\ComputerGames\Ui\Component\Listing\Column\ImageThumbnail"
                component="Magento_Ui/js/grid/columns/thumbnail" sortOrder="0" displayArea="generalarea">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="source" xsi:type="string">games</item>
                </item>
            </argument>
            <settings>
                <label translate="true">Image</label>
                <hasPreview>1</hasPreview>
            </settings>
        </column>
        <actionsColumn name="actions" class="Vendor\ComputerGames\Ui\Component\Listing\Column\GameActions"
                       sortOrder="200">
            <settings>
                <indexField>entity_id</indexField>
            </settings>
        </actionsColumn>
    </columns>
</listing>

\Vendor\ComputerGames\Ui\Component\Listing\Column\ImageThumbnail

<?php

declare(strict_types=1);
namespace Vendor\ComputerGames\Ui\Component\Listing\Column;

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

class ImageThumbnail extends Column
{
    /**
     * @var string
     */
    protected string $subDir = 'computer/image';

    public const ALT_FIELD = 'title';

    /**
     * @var StoreManagerInterface
     */
    protected StoreManagerInterface $storeManager;

    /**
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param Image $imageHelper
     * @param UrlInterface $urlBuilder
     * @param StoreManagerInterface $storeManager
     * @param array $components
     * @param array $data
     */
    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);
    }

    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     * @throws NoSuchEntityException
     */
    public function prepareDataSource(array $dataSource): array
    {
        if (isset($dataSource['data']['items'])) {
            $fieldName = $this->getData('name');
            foreach ($dataSource['data']['items'] as & $item) {
                $url = '';
                if ($item[$fieldName] != '') {
                    $url = $this->storeManager->getStore()->getBaseUrl(
                        UrlInterface::URL_TYPE_MEDIA
                    ) . $this->subDir . "/" . $item[$fieldName];
                }
                $item[$fieldName . '_src'] = $url;
                $item[$fieldName . '_alt'] = $this->getAlt($item) ?: '';
                $item[$fieldName . '_link'] = $this->urlBuilder->getUrl(
                    'games/game/edit',
                    ['game_id' => $item['game_id']]
                );
                $item[$fieldName . '_orig_src'] = $url;
            }
        }

        return $dataSource;
    }

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

\Vendor\ComputerGames\Ui\Component\Listing\Column\GameActions

<?php

declare(strict_types=1);
namespace Vendor\ComputerGames\Ui\Component\Listing\Column;

use Magento\Cms\Block\Adminhtml\Page\Grid\Renderer\Action\UrlBuilder;
use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Ui\Component\Listing\Columns\Column;

class GameActions extends Column
{
    /**
     * Url paths
     */
    const GAME_URL_PATH_EDIT = 'games/game/edit';
    const GAME_URL_PATH_DELETE = 'games/game/delete';
    /**
     * @var UrlBuilder
     */

    protected UrlBuilder $actionUrlBuilder;

    /**
     * @var UrlInterface
     */
    protected UrlInterface $urlBuilder;

    /**
     * @var string
     */
    private string $editUrl;

    /**
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param UrlBuilder $actionUrlBuilder
     * @param UrlInterface $urlBuilder
     * @param array $components
     * @param array $data
     * @param string $editUrl
     */
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        UrlBuilder $actionUrlBuilder,
        UrlInterface $urlBuilder,
        array $components = [],
        array $data = [],
        $editUrl = self::GAME_URL_PATH_EDIT
    ) {
        $this->urlBuilder = $urlBuilder;
        $this->actionUrlBuilder = $actionUrlBuilder;
        $this->editUrl = $editUrl;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }
    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource): array
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {
                $name = $this->getData('name');
                if (isset($item['game_id'])) {
                    $item[$name]['edit'] = [
                    'href' => $this->urlBuilder->getUrl(
                        $this->editUrl,
                        ['game_id' => $item['game_id']]
                    ),
                    'label' => __('Edit')
                ];
                    $item[$name]['delete'] = [
                        'href' => $this->urlBuilder->getUrl(
                            self::GAME_URL_PATH_DELETE,
                            ['game_id' => $item['game_id']]
                        ),
                        'label' => __('Delete'),
                        'confirm' => [
                        'title' => __('Delete ${ $.$data.name }'),
                        'message' => __('Are you sure you wan\'t to delete a ${
                        $.$data.name } record?')
                ]
            ];
                }
            }
        }
        return $dataSource;
    }
}

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.