4

I have ui component layout for an image field

     <field name="image">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Showcase Image</item>
                <item name="formElement" xsi:type="string">fileUploader</item>
                <item name="componentType" xsi:type="string">fileUploader</item>
                <item name="notice" xsi:type="string" translate="true">Allowed file types: ico, png, gif, jpg, jpeg, apng, svg. Not all browsers support all these formats!</item>
                <item name="maxFileSize" xsi:type="number">2097152</item>
                <item name="allowedExtensions" xsi:type="string">jpg jpeg gif png svg</item>
                <item name="uploaderConfig" xsi:type="array">
                    <item name="url" xsi:type="string">newstart_showcase_backend/showcase_image/upload</item>
                </item>
            </item>
        </argument>
    </field>

I have an save.php to save image name to database and another controller newstart_showcase_backend/showcase_image/upload to actually save the uploaded image to media folder. All these functions are working fine so far in "add new item" edit page. The real problem I have is image does not show when I open the existing item that I created. All other files are showing as expected, but not the image field. Any suggestion are appreciated. I can post more code here on demand if you need to check it. Thanks in advance.

Following is my main table A, and reference table B which stores store ID for each item in table A by referring the id

id  smallint(5) unsigned Auto Increment Entity ID
image   varchar(255)    Image Name
url varchar(255) [] Image Destination Url
caption varchar(255) NULL   Image Caption
start_date  date NULL    
end_date    date NULL    
order   smallint(6) [1] Image Ordering
status  tinyint(1) [1]  1 - Banner Enabled, 0 - Banner Disabled
created_at  timestamp [CURRENT_TIMESTAMP]   Created time
updated_at  timestamp [0000-00-00 00:00:00] Update time 

At "add new item" page, there is uploader enter image description here

Edit Page doesn't show image, and HOW CAN I MAKE IT SHOW HERE enter image description here

  • I'd figure out how it's loading showcase as a source and what's going on with that object. – LM_Fielding Oct 11 '16 at 15:42
  • Do you have a DataProvider like this? github.com/magento/magento2/blob/develop/app/code/Magento/… – LM_Fielding Oct 11 '16 at 15:49
  • @LM_Fielding, yes, I have DataProvider. But It's more like this one github.com/magento/magento2/blob/develop/app/code/Magento/Cms/…. Because I referred to the Cms_Page module the time I developed mine. I just check the above one you posted, seems image need particular handles, which is not present in Cms_Page DataProvider.php. Could you shed light on this? – Nero Oct 12 '16 at 1:13
  • At the edit time you are unable to show the image? – Manish Goswami Oct 12 '16 at 8:53
  • @LM_Fielding, Do you have completed working module which i can take a look at? – Nero Oct 18 '16 at 15:24
2

Your DataProvider class's getData() method should include the image name & the image URL as an array like shown below:

foreach ($items as $item) {
            $itemData = $item->getData();
            $imageName = $itemData['image_name']; // Your database field 
            unset($itemData['image_path']);
            $itemData['image_path'] = array(
                array(
                    'name'  =>  $imageName,
                    'url'   =>  $imageUrl // Should return a URL to view the image. For example, http://domain.com/pub/media/../../imagename.jpeg
                )
            );
            $this->loadedData[$item->getItemId()] = $itemData;
        }
0

You should have one file in location:- namespace\modulename\Ui\Component\Listing\Column['file_to_show_image'];
In my case its name is Thumbnail.php.
grid_item_form.xml is responsible to show the image at edit time:-

 <column name="profile" class="Dedicated\Employee\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">title</item>
                <item name="has_preview" xsi:type="string">1</item>
                <item name="label" xsi:type="string" translate="true">Thumbnail</item>
            </item>
        </argument>
    </column>  

My file name is Thumbnail.php and the code is :-
Image will be fetch form here.

<?php
namespace Dedicated\Employee\Ui\Component\Listing\Column;

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';

/**
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $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,
    UrlInterface $urlBuilder,
    StoreManagerInterface $storeManager,
    array $components = [],
    array $data = []
) {

    //die('d');
    $this->storeManager = $storeManager;
    $this->urlBuilder = $urlBuilder;
    parent::__construct($context, $uiComponentFactory, $components, $data);
}

/**
 * Prepare Data Source
 *
 * @param array $dataSource
 * @return array
 */
public function prepareDataSource(array $dataSource)
{

    if(isset($dataSource['data']['items'])) {
        $fieldName = $this->getData('name');
        //print_r($fieldName); die();
        foreach($dataSource['data']['items'] as & $item) {
            $url = '';
            if($item[$fieldName] != '') {
                $url = $this->storeManager->getStore()->getBaseUrl(
                    \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
                ).'dedicated/employees/'.$item[$fieldName];
            }
            $item[$fieldName . '_src'] = $url;
            $item[$fieldName . '_alt'] = $this->getAlt($item) ?: '';
            $item[$fieldName . '_link'] = $this->urlBuilder->getUrl(
                'employee/entity_id/edit',
                ['entity_id' => $item['entity_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;
}

}

If you are facing any problem then let me know.

We list the image in two cashes :-

1.In listing page.
2.Edit or Update Page

Where do you want to show the image or fetch the image ? or show me some screenshot so I could solve it better.

  • thank you for your answer first. It seems you are talking about showing image in grid column. But I meant form field. I'd like to try your solution, but it doesn't make up for me at first glance. Or maybe I can't get your point clearly. – Nero Oct 12 '16 at 14:02
  • This code is for edit action when you edit the grid image will be fetch from Thumbnail.php.Are you still unable to get the answer ? – Manish Goswami Oct 13 '16 at 2:30
  • I have edited the answer. – Manish Goswami Oct 13 '16 at 2:40
  • I updated my question. – Nero Oct 13 '16 at 14:59
  • Since the grid (also called listing) is also able to update the row (by click on the row), I'm afraid there is misunderstanding between you and me. If your solution can make the image show in a form, then I will think the concept of (grid) column and (form) field are totally been messed up and cause lots of trouble to me. – Nero Oct 13 '16 at 15:07
0

You not setData for image in your DataProvider that why image not show up
DataProvider defined in your ui-component/yourform.xml

Usually it located in \Namespace\Module\Model\Entity\DataProvider

/**
 * DataProvider for your form
 */
class DataProvider extends AbstractDataProvider
{
/** @var array **/
protected $loadedData;

/**
 * Get data from provider and populate
 * @param void
 * @return array
 */
public function getData()
{

    if (isset($this->loadedData)) {
        return $this->loadedData;
    }


    if ($menuId) {
        $items = $this->collection->getItems();

        /** @var \Namespace\Module\Model\YourItem $item */
        foreach ($items as $item) {
            $_data = $item->getData();
            $item->load($item->getId());

            if (isset($_data['image'])) {
                $image = [];
                $image[0]['name'] = $item->getImagePath();
                $image[0]['url'] = $this->imageModel->getMediaUrl().'item/image'.$item->getImagePath();
                $_data['image'] = $image;
            }
            $item->setData($_data);
            $this->loadedData[$item->getId()] = $_data;
        }

    }

    return $this->loadedData;
  }
}

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.