I have created custom Backend grid and Ui form to add image slider and it is working good in Backend. In Backend I have fetched the image by getting media url.In frontend, have fetched the image name and from database and also fetched media url .But I need to fetch the image and show it in front end. Please suggest me a solution to do.
This is what i got using below codes.
Block\ImageSlider.php
<?php
namespace OX\HomeSlider\Block;
use Magento\Framework\View\Element\Template\Context;
use OX\HomeSlider\Model\Post;
use Magento\Framework\View\Element\Template;
//use \Magento\Store\Model\StoreManagerInterface
class ImageSlider extends Template
{
protected $storeManager;
public function __construct(Context $context, Post $model, \Magento\Store\Model\StoreManagerInterface $storeManager)
{
$this->model = $model;
$this->storeManager = $storeManager;
parent::__construct($context);
}
public function getCollection()
{
$collection = $this->model->getCollection();
return $collection;
}
public function getMediaUrl()
{
$mediaUrl = $this->storeManager->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
return $mediaUrl;
}
DataProvider.php
<?php
namespace namspace\HomeSlider\Model;
use namspace\HomeSlider\Model\ResourceModel\Post\CollectionFactory;
use Magento\Store\Model\StoreManagerInterface;
class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{
protected $collection;
protected $_loadedData;
protected $_storeManager;
public function __construct(
$name, $primaryFieldName, $requestFieldName, CollectionFactory $postCollectionFactory, StoreManagerInterface $storeManager, array $meta = [], array $data = []
)
{
$this->collection = $postCollectionFactory->create();
$this->_storeManager = $storeManager;
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
}
public function getData()
{
if (isset($this->_loadedData)) {
return $this->_loadedData;
}
$items = $this->collection->getItems();
foreach ($items as $item) {
$this->_loadedData[$item->getId()] = $item->getData();
if ($item->getImage()) {
// replace icon to your custom field name
$m['image'][0]['name'] = $item->getImage();
$m['image'][0]['url'] = $this->getMediaUrl().'homeslider/'.$item->getImage();
$fullData = $this->_loadedData;
$this->_loadedData[$item->getId()] = array_merge($fullData[$item->getId()], $m);
}
}
return $this->_loadedData;
}
public function getMediaUrl()
{
$mediaUrl = $this->_storeManager->getStore()
->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
return $mediaUrl;
}
}
view/frontend/templates/Imageslider.phtml
<h1><?php $collections = $this->getCollection(); ?></h1>
<?php
foreach($collections as $collection){
echo $collection->getImage();
}
?>
<h1><?php echo $am = $this->getMediaUrl().'homeslider/'.$collection->getImage(); ?></h1>
Best Answer
Try to update code like this