Magento 2 How to upload csv in admin and update data in custom admin-grid/table?How to create a custom import in Magento 2Magento admin add grid under a tab in custom moduleMagento 2 - change value in admin order grid columnCustom admin grid Excel XML export - result contains no rows data, only columns namesMagento 2: store selector for custom module in admin formCustom csv import to a custom tableMagento 2 - Custom module file upload configuration and save in custom module tableHow to render product name in UI component admin grid based off product id in a custom table in Magento 2Admin Grid Mass Action delete not working for custom module for Magento 2.2.4How to add dynamic row in custom module magento 2Magento 2 display certain rows from custom table in admin grid

Why no parachutes in the Orion AA2 abort test?

Shipped package arrived - didn't order, possible scam?

Does the sensor of a dslr count the number of photons that hits it?

Multi-user CRUD: Valid, Problem, or Error?

What's the big deal about the Nazgûl losing their horses?

Better random (unique) file name

Pressure in giant ball of water floating in space

Taking advantage when HR forgets to communicate the rules

Possibility to correct pitch from digital versions of records with the hole not centered

Is conquering your neighbors to fight a greater enemy a valid strategy?

Can a USB hub be used to access a drive from two devices?

Any way to meet code with 40.7% or 40.44% conduit fill?

Why is there paternal, for fatherly, fraternal, for brotherly, but no similar word for sons?

Do Goblin tokens count as Goblins?

Is a lowball salary then a part-time offer standard Japanese employment negotiations?

Why do Klingons use cloaking devices?

Is it acceptable that I plot a time-series figure with years increasing from right to left?

How would a sea turtle end up on its back?

Park the computer

My professor has told me he will be the corresponding author. Will it hurt my future career?

How do I talk to my wife about unrealistic expectations?

Groups where no elements commute except for the trivial cases

Does the Milky Way orbit around anything?

Taking my Ph.D. advisor out for dinner after graduation



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


How to create a custom import in Magento 2Magento admin add grid under a tab in custom moduleMagento 2 - change value in admin order grid columnCustom admin grid Excel XML export - result contains no rows data, only columns namesMagento 2: store selector for custom module in admin formCustom csv import to a custom tableMagento 2 - Custom module file upload configuration and save in custom module tableHow to render product name in UI component admin grid based off product id in a custom table in Magento 2Admin Grid Mass Action delete not working for custom module for Magento 2.2.4How to add dynamic row in custom module magento 2Magento 2 display certain rows from custom table in admin grid






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4















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 ?










share|improve this question
























  • Is it product csv?

    – Ravi Soni
    Jun 27 at 9:55











  • No its custom .csv. Below are the columns of table: Id, CustomerName, CertificationId. I am actually trying to update this grid if some one upload .csv through admin(store/config).

    – Dinesh Rajput
    Jun 27 at 9:58











  • Might this will help you: magento.stackexchange.com/questions/169419/…

    – Ravi Soni
    Jun 27 at 11:28

















4















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 ?










share|improve this question
























  • Is it product csv?

    – Ravi Soni
    Jun 27 at 9:55











  • No its custom .csv. Below are the columns of table: Id, CustomerName, CertificationId. I am actually trying to update this grid if some one upload .csv through admin(store/config).

    – Dinesh Rajput
    Jun 27 at 9:58











  • Might this will help you: magento.stackexchange.com/questions/169419/…

    – Ravi Soni
    Jun 27 at 11:28













4












4








4








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 ?










share|improve this question
















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 ?







custom custom-admin-grid






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 27 at 13:53







Dinesh Rajput

















asked Jun 27 at 9:22









Dinesh RajputDinesh Rajput

777 bronze badges




777 bronze badges












  • Is it product csv?

    – Ravi Soni
    Jun 27 at 9:55











  • No its custom .csv. Below are the columns of table: Id, CustomerName, CertificationId. I am actually trying to update this grid if some one upload .csv through admin(store/config).

    – Dinesh Rajput
    Jun 27 at 9:58











  • Might this will help you: magento.stackexchange.com/questions/169419/…

    – Ravi Soni
    Jun 27 at 11:28

















  • Is it product csv?

    – Ravi Soni
    Jun 27 at 9:55











  • No its custom .csv. Below are the columns of table: Id, CustomerName, CertificationId. I am actually trying to update this grid if some one upload .csv through admin(store/config).

    – Dinesh Rajput
    Jun 27 at 9:58











  • Might this will help you: magento.stackexchange.com/questions/169419/…

    – Ravi Soni
    Jun 27 at 11:28
















Is it product csv?

– Ravi Soni
Jun 27 at 9:55





Is it product csv?

– Ravi Soni
Jun 27 at 9:55













No its custom .csv. Below are the columns of table: Id, CustomerName, CertificationId. I am actually trying to update this grid if some one upload .csv through admin(store/config).

– Dinesh Rajput
Jun 27 at 9:58





No its custom .csv. Below are the columns of table: Id, CustomerName, CertificationId. I am actually trying to update this grid if some one upload .csv through admin(store/config).

– Dinesh Rajput
Jun 27 at 9:58













Might this will help you: magento.stackexchange.com/questions/169419/…

– Ravi Soni
Jun 27 at 11:28





Might this will help you: magento.stackexchange.com/questions/169419/…

– Ravi Soni
Jun 27 at 11:28










1 Answer
1






active

oldest

votes


















0














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="MagentoConfigBlockSystemConfigFormFieldFile" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" >
<label>Upload Latest NASM Table</label>
<backend_model>MagentoConfigModelConfigBackendFile</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="VendorModuleObserverUpdate" />
</event>




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




class Update implements ObserverInterface

protected $messageManager;



protected $_modelNasmFactory;

protected $csv;

public $_storeManager;

protected $_scopeConfig;

public function __construct(
MagentoFrameworkMessageManagerInterface $messageManager,
NasmFactory $modelNasmFactory,
MagentoFrameworkFileCsv $csv,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkAppConfigScopeConfigInterface $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 = MagentoStoreModelScopeInterface::SCOPE_STORES;
$uploadedCsvFilePath = $this->_scopeConfig->getValue("nasmsetting/nasmgeneral/nasm_certification_file_upload", $storeScope);

$pubMediaUrl = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::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 ZendLogWriterStream(BP . '/var/log/nasmlog.log');
$logger = new ZendLogLogger();
$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);









share|improve this answer

























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f279879%2fmagento-2-how-to-upload-csv-in-admin-and-update-data-in-custom-admin-grid-table%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    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="MagentoConfigBlockSystemConfigFormFieldFile" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" >
    <label>Upload Latest NASM Table</label>
    <backend_model>MagentoConfigModelConfigBackendFile</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="VendorModuleObserverUpdate" />
    </event>




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




    class Update implements ObserverInterface

    protected $messageManager;



    protected $_modelNasmFactory;

    protected $csv;

    public $_storeManager;

    protected $_scopeConfig;

    public function __construct(
    MagentoFrameworkMessageManagerInterface $messageManager,
    NasmFactory $modelNasmFactory,
    MagentoFrameworkFileCsv $csv,
    MagentoStoreModelStoreManagerInterface $storeManager,
    MagentoFrameworkAppConfigScopeConfigInterface $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 = MagentoStoreModelScopeInterface::SCOPE_STORES;
    $uploadedCsvFilePath = $this->_scopeConfig->getValue("nasmsetting/nasmgeneral/nasm_certification_file_upload", $storeScope);

    $pubMediaUrl = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::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 ZendLogWriterStream(BP . '/var/log/nasmlog.log');
    $logger = new ZendLogLogger();
    $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);









    share|improve this answer



























      0














      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="MagentoConfigBlockSystemConfigFormFieldFile" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" >
      <label>Upload Latest NASM Table</label>
      <backend_model>MagentoConfigModelConfigBackendFile</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="VendorModuleObserverUpdate" />
      </event>




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




      class Update implements ObserverInterface

      protected $messageManager;



      protected $_modelNasmFactory;

      protected $csv;

      public $_storeManager;

      protected $_scopeConfig;

      public function __construct(
      MagentoFrameworkMessageManagerInterface $messageManager,
      NasmFactory $modelNasmFactory,
      MagentoFrameworkFileCsv $csv,
      MagentoStoreModelStoreManagerInterface $storeManager,
      MagentoFrameworkAppConfigScopeConfigInterface $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 = MagentoStoreModelScopeInterface::SCOPE_STORES;
      $uploadedCsvFilePath = $this->_scopeConfig->getValue("nasmsetting/nasmgeneral/nasm_certification_file_upload", $storeScope);

      $pubMediaUrl = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::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 ZendLogWriterStream(BP . '/var/log/nasmlog.log');
      $logger = new ZendLogLogger();
      $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);









      share|improve this answer

























        0












        0








        0







        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="MagentoConfigBlockSystemConfigFormFieldFile" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" >
        <label>Upload Latest NASM Table</label>
        <backend_model>MagentoConfigModelConfigBackendFile</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="VendorModuleObserverUpdate" />
        </event>




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




        class Update implements ObserverInterface

        protected $messageManager;



        protected $_modelNasmFactory;

        protected $csv;

        public $_storeManager;

        protected $_scopeConfig;

        public function __construct(
        MagentoFrameworkMessageManagerInterface $messageManager,
        NasmFactory $modelNasmFactory,
        MagentoFrameworkFileCsv $csv,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoFrameworkAppConfigScopeConfigInterface $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 = MagentoStoreModelScopeInterface::SCOPE_STORES;
        $uploadedCsvFilePath = $this->_scopeConfig->getValue("nasmsetting/nasmgeneral/nasm_certification_file_upload", $storeScope);

        $pubMediaUrl = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::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 ZendLogWriterStream(BP . '/var/log/nasmlog.log');
        $logger = new ZendLogLogger();
        $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);









        share|improve this 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="MagentoConfigBlockSystemConfigFormFieldFile" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1" >
        <label>Upload Latest NASM Table</label>
        <backend_model>MagentoConfigModelConfigBackendFile</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="VendorModuleObserverUpdate" />
        </event>




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




        class Update implements ObserverInterface

        protected $messageManager;



        protected $_modelNasmFactory;

        protected $csv;

        public $_storeManager;

        protected $_scopeConfig;

        public function __construct(
        MagentoFrameworkMessageManagerInterface $messageManager,
        NasmFactory $modelNasmFactory,
        MagentoFrameworkFileCsv $csv,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoFrameworkAppConfigScopeConfigInterface $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 = MagentoStoreModelScopeInterface::SCOPE_STORES;
        $uploadedCsvFilePath = $this->_scopeConfig->getValue("nasmsetting/nasmgeneral/nasm_certification_file_upload", $storeScope);

        $pubMediaUrl = $this->_storeManager->getStore()->getBaseUrl(MagentoFrameworkUrlInterface::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 ZendLogWriterStream(BP . '/var/log/nasmlog.log');
        $logger = new ZendLogLogger();
        $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);










        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 18 hours ago









        Dinesh RajputDinesh Rajput

        777 bronze badges




        777 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f279879%2fmagento-2-how-to-upload-csv-in-admin-and-update-data-in-custom-admin-grid-table%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

            Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

            Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?