Magento – Magento 2 How to upload csv in admin and update data in custom admin-grid/table

customcustom-admin-grid

I am trying to upload csv that I have exported from existing admin grid. Adding additional data as perticular columnwise in same csv. Howcan I upload/import that new .csv in admin and update data in already created custom admin-grid/table ?

Best Answer

I have finally done this by observer and event. Admin field where I upload .csv file with format of current admin grid like name,certificationId.

Vendor/Module/etc/adminhtml/System.xml:

<section id="nasmsetting" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
        <class>separator-top</class>
        <label>Nasm Setting</label>
        <tab>nasm</tab>
        <resource>Vendor_Module::nasm_config</resource>
        <group id="nasmgeneral" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>General Settings</label>
            <field id="nasm_certification_file_upload" translate="label" type="Magento\Config\Block\System\Config\Form\Field\File" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" >
                 <label>Upload Latest NASM Table</label>
                <backend_model>Magento\Config\Model\Config\Backend\File</backend_model>
                <upload_dir config="system" scope_info="1">nasmcustomers</upload_dir>
                <comment>Upload new NASM credentials</comment>
            </field>
        </group></section>

Now Create events.xml: app/code/Vendor/Module/etc/adminhtml/events.xml Here I have used "nasmsetting" as defined in system.xml. Which will change/update in admin and call this observer.So event name "admin_system_config_changed_section_nasmsetting"

<?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="admin_system_config_changed_section_nasmsetting">
    <observer name="update_latest_nasm_table" instance="Vendor\Module\Observer\Update" />
</event>

Observer where I read .csv and update table data: app/code/Vendor/Module/Observer/Update.php

<?php 
namespace Vendor\Module\Observer; 
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Vendor\Module\Model\NasmFactory;

class Update implements ObserverInterface
{
protected $messageManager;

protected $_modelNasmFactory;

protected $csv;

public $_storeManager;

protected $_scopeConfig;

public function __construct(
    \Magento\Framework\Message\ManagerInterface $messageManager,
    NasmFactory $modelNasmFactory,
    \Magento\Framework\File\Csv $csv,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
)
{    
    $this->messageManager = $messageManager; 
    $this->_modelNasmFactory = $modelNasmFactory;
    $this->csv = $csv;   
    $this->_storeManager = $storeManager;
    $this->_scopeConfig = $scopeConfig;
}

/**
 * Below is the method that will fire whenever the event runs!
 *
 * @param Observer $observer
 */
public function execute(Observer $observer)
{
    try{
        $model = $this->_modelNasmFactory->create();
        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORES;
        $uploadedCsvFilePath = $this->_scopeConfig->getValue("nasmsetting/nasmgeneral/nasm_certification_file_upload", $storeScope);

        $pubMediaUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
        $uploadedCsv = $pubMediaUrl."nasmcustomers/".$uploadedCsvFilePath;

        if($uploadedCsvFilePath != ''){

            $handle = fopen($uploadedCsv, "r");

            $csv = array_map("str_getcsv", file($uploadedCsv,FILE_SKIP_EMPTY_LINES));
            array_shift($csv);

            // If NASM IDs exist truncate table
            // File uploaded will have IDs already in the database, not just new ones
            if (!empty($model)) {
                $connection = $model->getResource()->getConnection();
                $tableName = $model->getResource()->getMainTable();
                $connection->truncateTable($tableName);
            }

            foreach ($csv as $i=>$row) {
                $customerName = $row[0]; //customername
                $certificationId = $row[1]; //certificationId
                $data = array('nasm_customer_name' => $customerName, 'nasm_code' => $certificationId);
                $model->setData($data);
                $model->save();
            }
        }
    }catch(Exception $e) {

        $writer = new \Zend\Log\Writer\Stream(BP . '/var/log/nasmlog.log');
        $logger = new \Zend\Log\Logger();
        $logger->addWriter($writer);
        $error_message = "Unable to read csv file. Error: " . $e->getMessage() . '. See exception.log for full error log.';

        $this->messageManager->addError($error_message);
        $logger->info($e);
    }
}

}`

Related Topic