Professional CodeIgniter

(singke) #1

Chapter 7: Improving the Dashboard


197


Please note that the SQL query is now pulling from the Products table.

Here ’ s the controller function export() in admin/products:

function export(){
$this- > load- > helper(‘download’);
$csv = $this- > MProducts- > exportCsv();
$name = “product_export.csv”;
force_download($name,$csv);
}

Again, all you ’ re doing is calling the model function and then piping that data into force_download().

Finally, here ’ s the link inserted into the admin_products_home view:

< p > < ?php echo anchor(“admin/products/create”, “Create new product”);? > | < ?php echo
anchor(“admin/products/export”,”Export”);? > < /p >

Go ahead and give the Export link a test. You should see a download dialog box appear, and it should
feature “ product_export.csv ” as the filename, as shown in Figure 7 - 5.

Figure 7-5

Importing a CSV Import Library for Products


As hinted at above, building an import function takes a lot more work than just exporting. Why is that?
Well, the short answer is that you are accepting data from a user, and users can make mistakes. They might
not line up their data columns right. Or they might not give you the kind of data you ’ re expecting — for
example, you may be expecting a category_id field, but they give you the name of a category.

There ’ s enough complexity in this kind of application that you may be sorely tempted to find a third -
party CSV import tool and add it to your libraries and helpers. In point of fact, a class called CSVReader
can be found in the CodeIgniter wiki area, and you ’ re going to use the basic functionality provided by
this class to facilitate your efforts. CSVReader was authored by Pierre Jean Turpeau and is available at
Free download pdf