2

How to show an image as "Option Label" in admin form multi-select field in Magento 2

enter image description here

Multi-Select Field

$fieldset->addField(
            'flag',
            'multiselect',
            [
                'name'        => 'flag',
                'label'    => __('Name'),
                'required'     => true,
                'values'   =>  $this->appliedFlags->toOptionArray(),
                'note'     => 'Set flags to column'
            ]
        );

options

<?php

namespace Vendor\Module\Ui\Component\Listing\Column;

class Flagoptions implements \Magento\Framework\Option\ArrayInterface
{
    const IMAGE_HEIGHT = '25';
    const IMAGE_STYLE = 'display: block;';

    public function __construct(
        
         \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
       
        $this->_storeManager = $storeManager;
    }

    public function toOptionArray()
    {
        $height =  self::IMAGE_HEIGHT;
        $style =  self::IMAGE_STYLE;
        $options =array();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $collection = $objectManager->create('Vendor\Module\Model\ResourceModel\Orderflag\Collection')
            ->addFieldToSelect(array('flag_id','name', 'image_icon'));
        $options[] = array( 'label' => 'NONE', 'value' => '-1'  );
        if( $collection->getSize() ){
             foreach ( $collection  as $flag) {
                 $srcImage = $this->_storeManager->getStore()
                        ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA) .$flag->getData('image_icon');
                 $ext = pathinfo($srcImage, PATHINFO_EXTENSION);
                 if($ext != '')
                 {
                    $image ="<img src='" . $srcImage . "' height='" . $height . "'/>";
                    $name = $flag->getData('name');

                    $label = $image.ucfirst($name);
                        
                }        
                 $options[] = array( 
                 'label' => $label,
                 'value' => $flag->getData('flag_id')
                );
             }
         }
      
       
        return $options;
    }
}
7
0

I think NO way to do if you using default magento/ui template. Because your code is using magento/ui component ui/form/element/multiselect. In template have this code optionsText: 'label'. So I think you should create custom template for this element.

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.