Question

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 !

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top