1

Anybody please help me to implement the current product image upload functionality used in Magento2 for my custom module. I tried different ideas posted in different websites. But not getting the result properly. enter image description here

Please find my code below:

adminhtml_gallery_category_edit.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-1column"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">

            <uiComponent name="edit_form"/>

            <referenceContainer name="edit_form">
                <block name="gallery" class="[Vendor]\[Module]\Block\Adminhtml\Grid\Helper\Form\Gallery">
                    <arguments>
                        <argument name="config" xsi:type="array">
                            <item name="label" xsi:type="string" translate="true">Images</item>
                            <item name="collapsible" xsi:type="boolean">true</item>
                            <item name="opened" xsi:type="boolean">false</item>
                            <item name="sortOrder" xsi:type="string">22</item>
                            <item name="canShow" xsi:type="boolean">true</item>
                            <item name="componentType" xsi:type="string">fieldset</item>
                        </argument>
                    </arguments>
                    <block class="[Vendor]\[Module]\Block\Adminhtml\Gallery\Helper\Form\Gallery\Content" as="content" template="[Vendor]_[Module]::helper/gallery.phtml">
                        <arguments>
                            <argument name="config" xsi:type="array">
                                <item name="parentComponent" xsi:type="string">edit_form.edit_form.block_gallery.block_gallery</item>
                            </argument>
                        </arguments>
                    </block>
                </block>
            </referenceContainer>
        </referenceContainer>
    </body>
</page>

Contnet.php

<?php


namespace [Vendor]\[Module]\Block\Adminhtml\Gallery\Helper\Form\Gallery;

use Magento\Backend\Block\Media\Uploader;
use Magento\Framework\View\Element\AbstractBlock;
use Magento\Framework\App\Filesystem\DirectoryList;

class Content extends \Magento\Backend\Block\Widget

{

    protected $_mediaConfig;

    protected $_template = '[Vendor]_[Module]::helper/gallery.phtml';


    protected $_jsonEncoder;


    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Framework\Json\EncoderInterface $jsonEncoder,
        \Magento\Catalog\Model\Product\Media\Config $mediaConfig,
        array $data = []
    ) {
        $this->_jsonEncoder = $jsonEncoder;
        $this->_mediaConfig = $mediaConfig;
        parent::__construct($context, $data);
    }

    protected function _prepareLayout()
    {
        $this->addChild('uploader', 'Magento\Backend\Block\Media\Uploader');

        $this->getUploader()->getConfig()->setUrl(
            $this->_urlBuilder->addSessionParam()->getUrl('gallery/upload')
        )->setFileField(
            'image'
        )->setFilters(
            [
                'images' => [
                    'label' => __('Images (.gif, .jpg, .png)'),
                    'files' => ['*.gif', '*.jpg', '*.jpeg', '*.png'],
                ],
            ]
        );

        $this->_eventManager->dispatch('catalog_product_gallery_prepare_layout', ['block' => $this]);

        return parent::_prepareLayout();
    }


    public function getUploader()
    {
        return $this->getChildBlock('uploader');
    }


    public function getUploaderHtml()
    {
        return $this->getChildHtml('uploader');
    }


    public function getJsObjectName()
    {
        return $this->getHtmlId() . 'JsObject';
    }


    public function getAddImagesButton()
    {
        return $this->getButtonHtml(
            __('Add New Images'),
            $this->getJsObjectName() . '.showUploader()',
            'add',
            $this->getHtmlId() . '_add_images_button'
        );
    }


    public function getImagesJson()
    {
        $value = $this->getElement()->getImages();
        if (is_array($value) &&
            array_key_exists('images', $value) &&
            is_array($value['images']) &&
            count($value['images'])
        ) {
            $directory = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA);
            $images = $this->sortImagesByPosition($value['images']);
            foreach ($images as &$image) {
                $image['url'] = $this->_mediaConfig->getMediaUrl($image['file']);
                $fileHandler = $directory->stat($this->_mediaConfig->getMediaPath($image['file']));
                $image['size'] = $fileHandler['size'];
            }
            return $this->_jsonEncoder->encode($images);
        }
        return '[]';
    }


    private function sortImagesByPosition($images)
    {
        if (is_array($images)) {
            usort($images, function ($imageA, $imageB) {
                return ($imageA['position'] < $imageB['position']) ? -1 : 1;
            });
        }
        return $images;
    }


    public function getImagesValuesJson()
    {
        $values = [];
        foreach ($this->getMediaAttributes() as $attribute) {
            /* @var $attribute \Magento\Eav\Model\Entity\Attribute */
            $values[$attribute->getAttributeCode()] = $this->getElement()->getDataObject()->getData(
                $attribute->getAttributeCode()
            );
        }
        return $this->_jsonEncoder->encode($values);
    }


    public function getImageTypes()
    {
        $imageTypes = [];
        foreach ($this->getMediaAttributes() as $attribute) {
            /* @var $attribute \Magento\Eav\Model\Entity\Attribute */
            $imageTypes[$attribute->getAttributeCode()] = [
                'code' => $attribute->getAttributeCode(),
                'value' => $this->getElement()->getDataObject()->getData($attribute->getAttributeCode()),
                'label' => $attribute->getFrontend()->getLabel(),
                'scope' => __($this->getElement()->getScopeLabel($attribute)),
                'name' => $this->getElement()->getAttributeFieldName($attribute),
            ];
        }
        return $imageTypes;
    }


    public function hasUseDefault()
    {
        foreach ($this->getMediaAttributes() as $attribute) {
            if ($this->getElement()->canDisplayUseDefault($attribute)) {
                return true;
            }
        }

        return false;
    }


    public function getMediaAttributes()
    {
        return $this->getElement()->getDataObject()->getMediaAttributes();
    }


    public function getImageTypesJson()
    {
        return $this->_jsonEncoder->encode($this->getImageTypes());
    }
}

Gallery.php

<?php


namespace [Vendor]\[Module]\Block\Adminhtml\Grid\Helper\Form;

use Magento\Framework\Registry;
use Magento\Catalog\Model\Product;
use Magento\Eav\Model\Entity\Attribute;
use Magento\Catalog\Api\Data\ProductInterface;

class Gallery extends \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery
{
    /**
     * @var here you set your ui form
     */
    protected $formName = 'edit_form';

}

helper/gallery.phtml

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/** @var $block \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery\Content */
$elementName = $block->getElement()->getName() . '[images]';
$formName = $block->getFormName();
?>

<?php
/** @var $block \Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery\Content */
$element = $block->getElement();
$elementToggleCode = $element->getToggleCode() ? $element->getToggleCode() : 'toggleValueElements(this, this.parentNode.parentNode.parentNode)';
?>

<div id="<?php echo $block->getHtmlId() ?>"
     class="gallery"
     data-mage-init='{"openVideoModal":{}}'
     data-parent-component="<?php echo $block->escapeHtml($block->getData('config/parentComponent')) ?>"
     data-images=""
     data-types=""
>

    <?php
    if (!$block->getElement()->getReadonly()):
        ?>
        <div class="image image-placeholder">
            <?php /* @escapeNotVerified */ echo $block->getUploaderHtml();
            ?>
            <div class="product-image-wrapper">
                <p class="image-placeholder-text">
                    <?php echo $block->escapeHtml(
                        __('Browse to find or drag image here')
                    ); ?>
                </p>
            </div>
        </div>
        <?php /* @escapeNotVerified */ echo $block->getChildHtml('additional_buttons'); ?>
        <?php
    endif;
    ?>
    <?php
    foreach ($block->getImageTypes() as $typeData):
        ?>
        <input name="<?php echo $block->escapeHtml($typeData['name']) ?>"
               data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"
               class="image-<?php echo $block->escapeHtml($typeData['code']) ?>"
               type="hidden"
               value="<?php echo $block->escapeHtml($typeData['value']) ?>"/>
        <?php
    endforeach;
    ?>
    <script id="<?php /* @escapeNotVerified */ echo $block->getHtmlId() ?>-template" data-template="image" type="text/x-magento-template">
        <div class="image item <% if (data.disabled == 1) { %>hidden-for-front<% } %>  <% if (data.video_url) { %>video-item<% } %>"
             data-role="image">
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][position]"
                   value="<%- data.position %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"
                   class="position"/>
            <% if (data.media_type !== 'external-video') {%>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][media_type]"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"
                   value="image"/>
            <% } else { %>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][media_type]"
                   value="<%- data.media_type %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <% } %>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][video_provider]"
                   value="<%- data.video_provider %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][file]"
                   value="<%- data.file %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][value_id]"
                   value="<%- data.value_id %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][label]"
                   value="<%- data.label %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][disabled]"
                   value="<%- data.disabled %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][removed]"
                   value="" class="is-removed"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][video_url]"
                   value="<%- data.video_url %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][video_title]"
                   value="<%- data.video_title %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][video_description]"
                   value="<%- data.video_description %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][video_metadata]"
                   value="<%- data.video_metadata %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>
            <input type="hidden"
                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][role]"
                   value="<%- data.video_description %>"
                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"/>

            <div class="product-image-wrapper">
                <img class="product-image"
                     data-role="image-element"
                     src="<%- data.url %>"
                     alt="<%- data.label %>"/>

                <div class="actions">
                    <button type="button"
                            class="action-remove"
                            data-role="delete-button"
                            title="<% if (data.media_type == 'external-video') {%>
                            <?php echo $block->escapeHtml(
                                __('Delete video')
                            ); ?>
                        <%} else {%>
                            <?php echo $block->escapeHtml(
                                __('Delete image')
                            ); ?>
                        <%}%>">
                    <span>
                        <% if (data.media_type == 'external-video') { %>
                        <?php echo $block->escapeHtml(
                            __('Delete video')
                        ); ?>
                        <% } else {%>
                        <?php echo $block->escapeHtml(
                            __('Delete image')
                        ); ?>
                        <%} %>
                    </span>
                    </button>
                    <div class="draggable-handle"></div>
                </div>
                <div class="image-fade"><span><?php echo $block->escapeHtml(
                            __('Hidden')
                        ); ?></span></div>
            </div>

            <div class="item-description">
                <% if (data.media_type !== 'external-video') {%>
                <div class="item-title" data-role="img-title"><%- data.label %></div>
                <div class="item-size">
                    <span data-role="image-dimens"></span>, <span data-role="image-size"><%- data.sizeLabel %></span>
                </div>
                <% } else { %>
                <div class="item-title" data-role="img-title"><%- data.video_title %></div>
                <% } %>
            </div>

            <ul class="item-roles" data-role="roles-labels">
                <?php
                foreach ($block->getImageTypes() as $typeData):
                    ?>
                    <li data-role-code="<?php echo $block->escapeHtml(
                        $typeData['code']
                    ) ?>" class="item-role item-role-<?php echo $block->escapeHtml(
                        $typeData['code']
                    ) ?>">
                        <?php echo $block->escapeHtml($typeData['label']) ?>
                    </li>
                    <?php
                endforeach;
                ?>
            </ul>
        </div>
    </script>

    <script data-role="img-dialog-container-tmpl" type="text/x-magento-template">
        <div class="image-panel" data-role="dialog">
        </div>
    </script>

    <script data-role="img-dialog-tmpl" type="text/x-magento-template">
        <div class="image-panel-preview">
            <img src="<%- data.url %>" alt="<%- data.label %>" />
        </div>
        <div class="image-panel-controls">
            <strong class="image-name"><%- data.label %></strong>

            <fieldset class="admin__fieldset fieldset-image-panel">
                <div class="admin__field field-image-description">
                    <label class="admin__field-label" for="image-description">
                        <span><?php /* @escapeNotVerified */ echo __('Alt Text')?></span>
                    </label>

                    <div class="admin__field-control">
                            <textarea data-role="image-description"
                                      rows="3"
                                      class="admin__control-textarea"
                                      name="<?php /* @escapeNotVerified */
                                      echo $elementName
                                      ?>[<%- data.file_id %>][label]"><%- data.label %></textarea>
                    </div>
                </div>

                <div class="admin__field field-image-role">
                    <label class="admin__field-label">
                            <span><?php echo $block->escapeHtml(
                                    __('Role')
                                ); ?></span>
                    </label>
                    <div class="admin__field-control">
                        <ul class="multiselect-alt">
                            <?php
                            foreach ($block->getMediaAttributes() as $attribute) :
                                ?>
                                <li class="item">
                                    <label>
                                        <input class="image-type"
                                               data-role="type-selector"
                                               data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"
                                               type="checkbox"
                                               value="<?php echo $block->escapeHtml(
                                                   $attribute->getAttributeCode()
                                               ) ?>"
                                        />
                                        <?php /* @escapeNotVerified */ echo $block->escapeHtml(
                                            $attribute->getFrontendLabel()
                                        ) ?>
                                    </label>
                                </li>
                                <?php
                            endforeach;
                            ?>
                        </ul>
                    </div>
                </div>

                <div class="admin__field admin__field-inline field-image-size" data-role="size">
                    <label class="admin__field-label">
                        <span><?php /* @escapeNotVerified */ echo __('Image Size') ?></span>
                    </label>
                    <div class="admin__field-value" data-message="<?php /* @escapeNotVerified */ echo __('{size}') ?>"></div>
                </div>

                <div class="admin__field admin__field-inline field-image-resolution" data-role="resolution">
                    <label class="admin__field-label">
                        <span><?php /* @escapeNotVerified */ echo __('Image Resolution') ?></span>
                    </label>
                    <div class="admin__field-value" data-message="<?php /* @escapeNotVerified */ echo __('{width}^{height} px') ?>"></div>
                </div>

                <div class="admin__field field-image-hide">
                    <div class="admin__field-control">
                        <div class="admin__field admin__field-option">
                            <input type="checkbox"
                                   id="hide-from-product-page"
                                   data-role="visibility-trigger"
                                   data-form-part="<?php /* @escapeNotVerified */ echo $formName ?>"
                                   value="1"
                                   class="admin__control-checkbox"
                                   name="<?php /* @escapeNotVerified */ echo $elementName ?>[<%- data.file_id %>][disabled]"
                            <% if (data.disabled == 1) { %>checked="checked"<% } %> />

                            <label for="hide-from-product-page" class="admin__field-label">
                                <?php echo $block->escapeHtml(
                                    __('Hide from Product Page')
                                ); ?>
                            </label>
                        </div>
                    </div>
                </div>
            </fieldset>
        </div>
    </script>
    <div id="<?php /* @noEscape */ echo $block->getNewVideoBlockName();?>" style="display:none">
        <?php /* @escapeNotVerified */ echo $block->getFormHtml();?>
        <div id="video-player-preview-location" class="video-player-sidebar">
            <div class="video-player-container"></div>
            <div class="video-information title">
                <label><?php echo $block->escapeHtml(
                        __('Title:')
                    ); ?> </label><span></span>
            </div>
            <div class="video-information uploaded">
                <label><?php echo $block->escapeHtml(
                        __('Uploaded:')
                    ); ?> </label><span></span>
            </div>
            <div class="video-information uploader">
                <label><?php echo $block->escapeHtml(
                        __('Uploader:')
                    ); ?> </label><span></span>
            </div>
            <div class="video-information duration">
                <label><?php echo $block->escapeHtml(
                        __('Duration:')
                    ); ?> </label><span></span>
            </div>
        </div>
    </div>

    <?php echo $block->getChildHtml('new-video'); ?>
</div>
<script>
    jQuery('body').trigger('contentUpdated');
</script>

ui_component/edit_form.xml

<?xml version="1.0"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    </form>
  • I already tried that one. But not getting a proper result. – VIPIN A ROY Apr 5 '17 at 6:37
  • I'm only getting a blank page with an "Add Video" button. – VIPIN A ROY Apr 5 '17 at 9:32
  • @VIPINAROY please add your code – Ashar Riaz Apr 7 '17 at 6:11
  • @VIPIN A ROY maybe you are missing something so add your code what you have done till now – Ashar Riaz Apr 7 '17 at 6:29
  • @AsharRiaz Updated the question and included the code there. – VIPIN A ROY Apr 7 '17 at 6:45
2

In your layout add this code

<?xml version="1.0" ?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <update handle="editor"/>
    <head>
    <css src="jquery/fileUploader/css/jquery.fileupload-ui.css"/>
    <css src="Magento_Catalog::catalog/category-selector.css"/>
    <css src="Magento_Catalog::product/product.css"/>

</head>
<body>
    <referenceContainer name="content">
        <uiComponent name="yourform_name"/>
        <referenceContainer name="yourform_name">
        <block name="gallery" class="Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Gallery">
            <arguments>
                <argument name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Gallery Images</item>
                    <item name="collapsible" xsi:type="boolean">true</item>
                    <item name="opened" xsi:type="boolean">false</item>
                    <item name="sortOrder" xsi:type="string">22</item>
                    <item name="canShow" xsi:type="boolean">true</item>
                    <item name="componentType" xsi:type="string">fieldset</item>
                </argument>
            </arguments>
            <block class="[Vendor]\[Module]\Block\Adminhtml\Gallery\Helper\Form\Gallery\Content" as="content">
                <arguments>
                    <argument name="config" xsi:type="array">
                        <item name="parentComponent" xsi:type="string">yourform_name.yourform_name.block_gallery.block_gallery</item>
                    </argument>
                </arguments>

            </block>
        </block>
    </referenceContainer>

    </referenceContainer>

</body

Now in Content.php

 namespace [Vendor]\[Module]\Block\Adminhtml\Gallery\Helper\Form\Gallery;

use Magento\Backend\Block\Media\Uploader;
use Magento\Framework\View\Element\AbstractBlock;



  class Images extends \Magento\Backend\Block\Widget

{

    /**
     * @var string
 */
protected $_template = 'modulename/gallery.phtml';

/**
 * @var \Magento\Catalog\Model\Product\Media\Config
 */
protected $_mediaConfig;

/**
 * @var \Magento\Framework\Json\EncoderInterface
 */
protected $_jsonEncoder;

public $objectMgr;

/**
 * @param \Magento\Backend\Block\Template\Context     $context
 * @param \Magento\Framework\Json\EncoderInterface    $jsonEncoder
 * @param \Magento\Catalog\Model\Product\Media\Config $mediaConfig
 * @param array                                       $data
 */
public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Framework\Json\EncoderInterface $jsonEncoder,
    \Company\Modulename\Model\Media\Config $mediaConfig,
    \Magento\Framework\Registry $coreRegister,
    \Magento\Framework\ObjectManagerInterface $objectManager,
    array $data = []
) {

    $this->_jsonEncoder = $jsonEncoder;
    $this->_mediaConfig = $mediaConfig;
    $this->_coreRegister = $coreRegister;
    $this->objectMgr = $objectManager;
    parent::__construct($context, $data);
}

/**
 * @return AbstractBlock
 */
protected function _prepareLayout()
{
    $this->addChild('uploader', 'Magento\Backend\Block\Media\Uploader');

    $this->getUploader()->getConfig()->setUrl(
        $this->_urlBuilder->addSessionParam()->getUrl('yourcontroller/upload')
    )->setFileField(
        'image'
    )->setFilters(
        [
                'images' => [
                    'label' => __('Images (.gif, .jpg, .png)'),
                    'files' => ['*.gif', '*.jpg', '*.jpeg', '*.png'],
                ],
            ]
    );

    $this->_eventManager->dispatch('yourmodulename_prepare_layout', ['block' => $this]);

    return parent::_prepareLayout();
}

public function images()
{
    $images = $this->_coreRegister->registry('photogallery_img');
    $img_data = $images->getData();

    return $img_data;
}

/**
 * Retrieve uploader block
 *
 * @return Uploader
 */
public function getUploader()
{
    return $this->getChildBlock('uploader');
}

/**
 * Retrieve uploader block html
 *
 * @return string
 */
public function getUploaderHtml()
{
    return $this->getChildHtml('uploader');
}

/**
 * @return string
 */
public function getJsObjectName()
{
    return $this->getHtmlId() . 'JsObject';
}

/**
 * @return string
 */
public function getAddImagesButton()
{
    return $this->getButtonHtml(
        __('Add New Images'),
        $this->getJsObjectName() . '.showUploader()',
        'add',
        $this->getHtmlId() . '_add_images_button'
    );
}

/**
 * Retrieve media attributes
 *
 * @return array
 */
public function getMediaAttributes()
{
    return $this->getElement()->getDataObject()->getMediaAttributes();
}

/**
 * @return string
 */
public function getImagesJson()
{

    $value['images'] = $this->images();
    if (is_array($value['images']) && count($value['images']) > 0) {
        foreach ($value['images'] as &$image) {
            $image['url'] = $this->_mediaConfig->getMediaUrl($image['img_name']);
            $image['file'] = $image['img_name'];
            $image['label'] = $image['img_label'];
            $image['value_id'] = $image['img_id'];
            $image['photogallery_id'] = $image['photogallery_id'];
            $image['description'] = $image['img_description'];
        }
        return $this->_jsonEncoder->encode($value['images']);
    }

    return '[]';
}

/**
 * @return string
 */
public function getImagesValuesJson()
{
    $values = [];
    return $this->_jsonEncoder->encode($values);
}

/**
 * Get image types data
 *
 * @return array
 */
public function getImageTypes()
{
    $imageTypes = [];
    foreach ($this->images() as $attribute) {
        /* @var $attribute \Magento\Eav\Model\Entity\Attribute */
        $imageTypes['image'] = [
            'code' => 'image',
            'value' => $attribute['img_name'],
            'label' => $attribute['img_label'],
            'scope' => 'Store View',
            'name' => 'gallery[image]',
        ];
    }
    return $imageTypes;
}

/**
 * @return string
 */
public function getImageTypesJson()
{
    return $this->_jsonEncoder->encode($this->getImageTypes());


 }
}

In Config.php

<?php




namespace Company\Module\Model\Media;


class Config implements ConfigInterface
{

    protected $storeManager;
/**
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 */
public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager)
{
    $this->storeManager = $storeManager;
}

/**
 * Filesystem directory path of product images
 * relatively to media folder
 *
 * @return string
 */
public function getBaseMediaPathAddition()
{
    return 'photogallery/images';
}

/**
 * Web-based directory path of product images
 * relatively to media folder
 *
 * @return string
 */
public function getBaseMediaUrlAddition()
{
    return 'photogallery/images';
}

/**
 * @return string
 */
public function getBaseMediaPath()
{
    return 'photogallery/images';
}

/**
 * @return string
 */
public function getBaseMediaUrl()
{
    return $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) . 'photogallery/images';
}

/**
 * Filesystem directory path of temporary product images
 * relatively to media folder
 *
 * @return string
 */
public function getBaseTmpMediaPath()
{
    return   $this->getBaseMediaPathAddition();
}

/**
 * @return string
 */
public function getBaseTmpMediaUrl()
{
    return $this->storeManager->getStore()->getBaseUrl(
        \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
    )  . $this->getBaseMediaUrlAddition();
}

/**
 * @param string $file
 * @return string
 */
public function getMediaUrl($file)
{
    return $this->getBaseMediaUrl() . '/' . $this->_prepareFile($file);
}

/**
 * @param string $file
 * @return string
 */
public function getMediaPath($file)
{
    return $this->getBaseMediaPath() . '/' . $this->_prepareFile($file);
}

/**
 * @param string $file
 * @return string
 */
public function getTmpMediaUrl($file)
{
    return $this->getBaseTmpMediaUrl() . '/' . $this->_prepareFile($file);
}

/**
 * Part of URL of temporary product images
 * relatively to media folder
 *
 * @param string $file
 * @return string
 */
public function getTmpMediaShortUrl($file)
{
    return $this->getBaseMediaUrlAddition() . '/' . $this->_prepareFile($file);
}

/**
 * Part of URL of product images relatively to media folder
 *
 * @param string $file
 * @return string
 */
public function getMediaShortUrl($file)
{
    return $this->getBaseMediaUrlAddition() . '/' . $this->_prepareFile($file);
}

/**
 * @param string $file
 * @return string
 */
public function getTmpMediaPath($file)
{
    return $this->getBaseTmpMediaPath() . '/' . $this->_prepareFile($file);
}

/**
 * @param string $file
 * @return string
 */
protected function _prepareFile($file)
{
    return ltrim(str_replace('\\', '/', $file), '/');


  }
}

In ConfigInterface.php

    <?php

namespace Company\Module\Model\Media;

interface ConfigInterface
{
/**
 * Retrieve base url for media files
 *
 * @return string
 */
public function getBaseMediaUrl();

/**
 * Retrieve base path for media files
 *
 * @return string
 */
public function getBaseMediaPath();

/**
 * Retrieve url for media file
 *
 * @param  string $file
 * @return string
 */
public function getMediaUrl($file);

/**
 * Retrieve file system path for media file
 *
 * @param  string $file
 * @return string
 */


 public function getMediaPath($file);
}

Now change the paths and names accordingly

and on the top of gallery.phtml add below lines

 <?php
$elementName = 'gallery' . '[images]';
$formName = 'your_form';
$productMetadata = $block->objectMgr->create('\Magento\Framework\App\ProductMetadata');
?>
| improve this answer | |
  • Hi @Ashar Riaz Thank you so much for your help. Now the code improved alot. I found a small mistake in Content.php, the class name written as 'Images'. But now also I'm getting a blank screen. No errors are reported in any of the log files. – VIPIN A ROY Apr 7 '17 at 8:18
  • Content.php we need to correct protected $_template = 'modulename/gallery.phtml'; to protected $_template = 'modulename::gallery.phtml'; – VIPIN A ROY Apr 7 '17 at 8:43
  • @VIPINAROY Now working ? – Ashar Riaz Apr 7 '17 at 9:27
  • A blank page is giving and there is no errors. – VIPIN A ROY Apr 7 '17 at 9:55
  • then check your template file and try to echo in it – Ashar Riaz Apr 7 '17 at 10:01
0

@VIPIN A ROY

I implement same functionality with custom module
HERE I give you this link please follow this steps

| improve this answer | |
  • I integrated this solution, but getting only a blank page with an "Add Video" button. When I click on that button, nothing will happen. – VIPIN A ROY Apr 7 '17 at 4:42

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