4

I implemented a custom module Company/Module.

In the controller folder i have upload.php file.

I need to modify this file to display the output in a tabular form with sku and product image.

Please suggest me the possible ways.

Thank you in advance !

3
  • please check my answer and let me know if not solve. – Rohan Hapani Oct 5 '18 at 5:39
  • Happy to help :) Happy coding !! Please accept answer @Charan – Rohan Hapani Oct 5 '18 at 6:14
  • hi @charan, please check my answer. – mrfizh Oct 5 '18 at 7:51
2

if you want to display sku and image in the frontend as list based your csv upload, you can reference first from answer on this link, then continue make some modifying on the code.

on the Upload.php class file change code to be like this :

<?php
namespace Company\Module\Controller\Index;

class Upload extends \Magento\Framework\App\Action\Action
{

    protected $_productFactory;
    protected $_storeManager;
    protected $_registry;
    protected $resultPageFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Registry $registry
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->_productFactory = $productFactory;
        $this->_storeManager = $storeManager;
        $this->_registry = $registry;
        parent::__construct($context);
    }

    public function execute()
    {
        $file =  fopen($_FILES['file']['tmp_name'], "r");
        $header = fgetcsv($file); // get data headers and skip 1st row
        $summaryProduct = array();
        $required_data_fields = 3;

        while ( $row = fgetcsv($file, 3000, ",") ) {

            $data_count = count($row);
            if ($data_count < 1) {
                continue;
            }

            $data = array();
            $data = array_combine($header, $row);

            $productData = $this->getImagePathFromSku($data['sku']);

            if(is_array($productData) and !is_null($productData)) {
               array_push($summaryProduct, $productData); 
            }

        }

        $this->_registry->register('custom_summary_products', $summaryProduct);
        return $this->resultPageFactory->create();
    }

    public function getImagePathFromSku($sku)
    {
        $product = $this->_productFactory->create()->loadByAttribute('sku', $sku);

        if($product) {
            $mediaurl= $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
            $imagepath = $mediaurl.'catalog/product'.$product->getImage();
            $result = array('sku' => $sku, 'product_name'=> $product->getName(), 'path_image' => $imagepath);

            return $result;
        } else {
            return;
        }
    }
}

next step create layout xml file with name image_index_upload.xml on your Company/Module/view/frontend/layout folder, insert this code to the file :

<?xml version="1.0" ?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Company\Module\Block\Index\Lists" name="index.lists" template="Company_Module::index/lists.phtml" />
        </referenceContainer>
    </body>
</page>

create block class file with name Lists.php in the folder Company/Module/Block/Index folder, insert the file by this code :

<?php
namespace Company\Module\Block\Index;

class Lists extends \Magento\Framework\View\Element\Template
{
    protected $_register;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Registry $register,
        array $data = []
    ) {
        $this->_register = $register;
        parent::__construct($context, $data);
    }

    public function getRegisterData()
    {
        return $this->_register->registry('custom_summary_products');
    }
}

and last create file phtml to show sku and product image, create file lists.phtml on the Company/Module/view/frontend/templates, then insert this code on the file

<?php $resultData = $this->getRegisterData() ?>
<?php $count = sizeof($resultData) ?>

<table>
    <tr>
        <th><?php echo __('SKU') ?></th>
        <th><?php echo __('Product Name') ?></th>
        <th><?php echo __('Image') ?></th>
    </tr>
    <tbody>
        <?php for($i=0;$i<$count;$i++) : ?>
            <tr>
                <td><?php echo $resultData[$i]['sku'] ?></td>
                <td><?php echo $resultData[$i]['product_name'] ?></td>
                <td><img src="<?php echo $resultData[$i]['path_image'] ?>" style="with:130px;height:130px"/></td>
            </tr>
        <?php endfor; ?>
    </tbody>
</table>

don't forget after you finished update all code, execute this commands on your command-line :

php bin/magento cache:clean

php bin/magento setup:upgrade

here is an screenshot example for the result :

enter image description here

Hope this help.

4
  • Hi@mrfizh It is displaying blank page.in url i give like this localhost/magento 2/image.Can i remove any files from the previous implementation.for example Company\Module\view\frontend\layout image_index_index.xml. – charan Oct 5 '18 at 9:42
  • not, you cant..if you remove previous file you will get error. I've uploaded to git repository for the extension, please get on this url github.com/hafizhff/magento2ShowProductImageBySKU – mrfizh Oct 5 '18 at 10:16
  • Hi@mrfizh.Finally working fine.Thank you very much. – charan Oct 5 '18 at 10:30
  • glad to know that, okay you're welcome :) – mrfizh Oct 5 '18 at 10:31
1

Inject \Magento\Catalog\Api\ProductRepositoryInterfaceFactory in your constructor.

protected $_productRepository;

public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {

    $this->_productRepository = $productRepository;
}

We can get the image:

$product = $this->_productRepository->get($sku);
$product->getData('image');
$product->getData('thumbnail');
$product->getData('small_image');
1
  • Hi@Rohan Hapani I want to implement a custom module. My actual requirement is to upload a csv file which contains sku.and i want to get the product images for those skus.and i want the output in a tabular form with sku and product image.could you suggest me the possible solution. – charan Oct 5 '18 at 6:18
0

follow below code

public function __construct(\Magento\Catalog\Model\ProductFactory $productFactory)
{
    $this->productFactory = $productFactory;
}


public function execute()
{
 $sku='your-sku';
 $product = $this->productFactory->create();
 $productDetails = $product->load($product->getIdBySku($sku));
 $productDetails->getData('image');
 $productDetails->getData('thumbnail');
 $productDetails->getData('small_image');
}
0

First of all you are in need to load product based on your sku you can use product repository:

public function __construct(
    Context $context, 
    \Magento\Catalog\Model\ProductRepository $productRepo,
    \Magento\Catalog\Helper\ImageFactory $imageHelperFactory
) {
    parent::__construct($context);
    $this->_productRepo = $productRepo;
    $this->imageHelperFactory = $imageHelperFactory;
}

in execute function:

public function execute() {
    $productSku = 'Test';

    $repoProductById = $this->get($productSku);

    $productName = $repoProductById->getName();
    $productSku = $repoProductById->getSku();
    $imageUrl = $this->imageHelperFactory->create()->init($repoProductById, 'product_thumbnail_image')->getUrl();


    echo '<pre>';
    print_r($repoProductById->getData());
    exit;

}
4
  • Hi@Narendra i want to implement a custom module.my actual requirement is to upload a csv file which contains sku.and i want to display the output with sku and product image in a tabular form.could you pls suggest me the possible solution. – charan Oct 5 '18 at 6:09
  • Hi, your requirement is not clear to me. correct me if i am wrong. you want to upload a csv containing skus in backend and in frontend want to show skus with images. right ? – Narendra Vyas Oct 5 '18 at 6:16
  • Hi@Narendra.I want to implement this on my local host.i want to upload csv file in frontend only. – charan Oct 5 '18 at 6:19
  • I can tell you the approach, from frontend when you upload csv you will be in need to read that csv in controller, there you can get images from product collection as per sku in loop as described above. Create array of sku and images as you want and pass that to view, you can take help of blocks, blocks will render data to phtml their you can take a table structure – Narendra Vyas Oct 5 '18 at 6:27

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.