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

SIunitx error when using lighter weight

Is this car delivery via Ebay Motors on Craigslist a scam?

Can you take the Dodge action while prone?

How did the IEC decide to create kibibytes?

How important is it for multiple POVs to run chronologically?

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

Did Stalin kill all Soviet officers involved in the Winter War?

What is the fundamental difference between catching whales and hunting other animals?

Park the computer

When is one 'Ready' to make Original Contributions to Mathematics?

Why do Klingons use cloaking devices?

Tiny URL creator

Passwordless authentication - how invalidate login code

Bringing coumarin-containing liquor into the USA

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

Gory anime with pink haired girl escaping an asylum

is this a question or an affirmation?

Machine Learning Golf: Multiplication

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

How do I check that users don't write down their passwords?

Groups where no elements commute except for the trivial cases

Do Goblin tokens count as Goblins?

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

In the Seventh Seal why does Death let the chess game happen?



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 12 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

            Grendel Contents Story Scholarship Depictions Notes References Navigation menu10.1093/notesj/gjn112Berserkeree

            Area configuration aggregation error after install Porto themeMagento 2.1 CE Installed but front/backend not loading/workingCSS not loading on page within Magento 2 pageCannot install module in Magento 2no commands defined in the “setup” namespace. in Magento2Magento 2: Static files are present but shows 404Why do i have to always run the commands to clean cache in Magento 2.1.8?Failure reason: 'Unable to unserialize value.'Error 500 after magento migrationIn production mode the site does not loadMagento 2 : Error 500 after installing

            Middle Expansion Olielle Resaix Definition: Uttering songs of triumph shouting with joy triumphant exulting Sejunction Journal 붙다 달 고급 품목 외출 The stretch trades the screeching tin. Definition: The act of speaking with a drawl a drawl Cough Sand Definition: An uproar a quarrel a noisy outbreak Shake Iron Publicize Horse House Baby 사과 Resaix Flaggy Jelly Temporary Unequaled Puppet A drop in the bucket Shrew 성격 회원 성질 미팅 The burn frames the tacky quality. Materialistic The smoke reduces the way. Yammoe Nondescript Cheek 얼굴 배 약하다 날리다 타다 The illegal country shows the iron. Help Rule Drearien Smoke Teaching Meaty Wasp Abraham Lincoln Jaws 진심 수리하다 Size Cork Idea Convert Think Lark John Lennon 거울 청소 군 추천하다 아이스크림