Professional CodeIgniter

(singke) #1

Chapter 7: Improving the Dashboard


200


Now it ’ s time to work inside the admin/products controller. There you ’ re going to create an import()
function, which will test for the existence of a csvinit POST field. If it finds it, it will call the MProducts
model, run the importCsv() function, and then pass that data over to a view. This constitutes a preview
function so that users can be sure that they ’ re uploading the proper data.

function import(){
if ($this- > input- > post(‘csvinit’)){
$data[‘csv’] = $this- > MProducts- > importCsv();
$data[‘title’] = “Preview Import Data”;
$data[‘main’] = ‘admin_product_csv’;
$this- > load- > vars($data);
$this- > load- > view(‘dashboard’);

}elseif($this- > input- > post(‘csvgo’)){

}

}

Another small check here: If a different POST field is detected, one called csvgo , the system will commit
the CSV data to the Products database table. You ’ ll see more on that shortly. First, you need to build the
admin_product_csv view.

The admin_product_csv view doesn ’ t need to be complicated. All that ’ s needed is to take the data
from the parsed CSV lines and drop them all into a table, making sure that each table cell has an
accompanying hidden field with the relevant data from the CSV file. At the end of the form, you add a
hidden field that is named csvgo , and then you submit the entire thing back to the import() function.

What follows is the admin_product_csv view. The view opens with a simple check to make sure that the
incoming $csv array has lines in it and then opens with a form post to admin/products/import. Notice
that the form has a Cancel and a Submit button.

< ?php
if (count($csv)){
echo form_open(‘admin/products/import’);
echo form_submit(‘cancel’,’ < < start over’);
echo form_submit(‘submit’,’finalize import > > ’);
? >

After the preliminaries are finished, build the table header by looping through the first line of the $csv
array. Trim out any white space, and ignore any thumbnail or image data. (The administrative users like
Claudia or one of her employees can go back and upload images one at a time once they ’ re done
importing the CSV data.)

< table border=’1’ cellspacing=’0’ cellpadding=’5’ >
< tr valign=’top’ >
< ?php
$headers = array_keys($csv[0]);
foreach ($headers as $v){
$hdr = trim(str_replace(‘”’,’’,$v));
if ($hdr != ‘’ & & !eregi(“thumbnail”,$hdr) & & !eregi(“image”,$hdr)){
Free download pdf