Professional CodeIgniter

(singke) #1

Chapter 7: Improving the Dashboard


203


[line_1] = > Array
(
[id] = > 2
[name] = > Game 2
[shortdesc] = > This is a very good game.
[longdesc] = > What a product! You’ll love the way your kids will play with
this game all day long. It’s terrific!
[sizes] = >
[colors] = >
[grouping] = > tmyer
[status] = > active
[category_id] = > 3
[featured] = > true
[price] = > 19.95
)
)...

It doesn ’ t take too much of a leap to figure out how to send this data array to a special model function.
Before you do that, of course, you have to know whether you ’ re supposed to send the data on or the user
has clicked “ Start over. ”

Therefore, go back to your import() function and add another branch inside the elseif branch of the
logic. Inside that branch, you ’ ll check for the string “ finalize ” in the Submit button. If you find it, run a
function called csv2db() (which you ’ ll be building shortly) and use flash data to set a status update. If
not, set a different message. At the end of the process, redirect the user to the admin/products/index page.


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’)){
if (eregi(“finalize”, $this- > input- > post(‘submit’))){
$this- > MProducts- > csv2db();
$this- > session- > set_flashdata(‘message’,’CSV data imported’);
}else{
$this- > session- > set_flashdata(‘message’,’CSV data import cancelled’);
}
redirect(‘admin/products/index’,’refresh’);
}
}

The final part of the import feature is the MProducts function called csv2db(). This is an extremely
simple function that loops through the data array and performs either an insert or update function,
depending on whether it finds an ID field.


No further processing is necessary at that point, because the keys serve as database field names. As long
as they match what ’ s in the database, the data import will work. Remember to remove the submit and
csvgo fields from the data stream!

Free download pdf