Building a Product CSV Import Tool in OpenCart: Part 2

In our last tutorial we discussed how to implement an import tool, in which we created an import button and its front-end template. Today we’ll learn how we can directly import the bulk data from our computers to our OpenCart System. 

Let’s consider the hierarchy first. In the previous tutorial we implemented the export tool, which allows the user to download CSV sheets and alternate as needed. After that we implemented the import tool, which allows the user to upload/import that edited file/data. Previously we implemented the layout. In this article, we’ll implement the functionality.

1. Controller File

In our last tutorial, we created a controller which pushes us to the layout of the upload form. In the view file of the layout, we had an upload input where the user can upload a CSV as shown below:

Import CSV page
  1. Navigate to admin/controller/catalog/product.php.
  2. Find the importCSV() Function, which we created in the previous tutorial.
  3. Place if (($this->request->server['REQUEST_METHOD'] == 'POST') ) {} after it, to ensure that the code part will only be executed if the above form is submitted.
  4. Inside the above block of code, we will add the code explained step by step below.

1.1 Getting the File

The following code opens the submitted CSV file and handles it as a read-only.

1.2 Traverse Through Each Record

Now we need to get through each row of the CSV and save into our db. In this regard, we will be looping through the records and saving them accordingly.

1.3 Redirecting

After the importing is finished, the user must be redirected, so the following code redirects the user to the form and gives a success message.

Up to this point, we’ve created a function that only uploads the CSV, reads its data line by line and parses it to the model. Now we need to create a model as defined in the controller code, which is responsible for saving the parsed data into the db.

2. Model File

  1. Navigate to admin/model/catalog/product.php.
  2. Create a public function there named importCsvData($data).
  3. Inside the model function, we will add this code, which contains some queries to save the data.

Conclusion

So, today’s tutorial is all about providing a complete solution for the Export/Import system. We provide such a solution, in which users can edit/update their data. This solution is super easy to use and implement as well. I am looking forward to your feedback. Feel free to leave a comment or query below. Thank you!

Tags:

Comments

Related Articles