Professional CodeIgniter

(singke) #1

Chapter 7: Improving the Dashboard


195


All you need in this instance is a result set object, which you hand off to the csv_from_result()
method. That ’ s the first argument. The second argument is the field delimiter (the default is tab, but
you ’ ll want to set a comma). You want to set a comma because it ’ s the comma that makes it a comma -
separated file, as opposed to a tab - separated file. The third argument is the record delimiter (a good
suggestion is “ \n ” ). You want to set a new line ( “ \n ” ) as this is pretty much the universally agreed
notation for “ new record. ” It ’ s much easier to process each line of data that way with PHP when you
import the file.


Here ’ s the completed exportCsv() function:


function exportCsv(){
$this- > load- > dbutil();
$Q = $this- > db- > query(“select * from categories”);
return $this- > dbutil- > csv_from_result($Q,”,”,”\n”);
}

Please note that csv_from_result() doesn ’ t actually create a file, just a CSV string of text. To create a
downloadable file, you ’ ll need to do some work in the appropriate controller.


Speaking of which, let ’ s turn our attention to the admin/categories controller. Again, you ’ ll need to build
a new function, one called export() .This function is also pretty simple, but it has two very important
jobs. First, it must call the new model function, capturing the CSV string in a variable. Then it must
invoke the force_download() feature of the Download helper to create a file that is downloaded to the
user ’ s desktop or laptop.


The force_download() function is described in Chapter 3. It ’ s basically a very useful CodeIgniter
helper function that writes the headers in such a way that the data you create get captured in a file. Of
course, along the way you need to also provide the function with a filename (in this case, category_export
.csv ).

Here ’ s the export() function in all its six - line glory. If you have written export functions in the past,
please note that all of this was accomplished with 11 lines of code (five in the model, six in the
controller).

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

}

What ’ s left to do? You need to add a link to the admin_categories_home view that will invoke the
controller function. A good place for it is next to the Create link. That part of the view is presented below.

< h1 > < ?php echo $title;? > < /h1 >
< p > < ?php echo anchor(“admin/categories/create”, “Create new category”);? > | < ?php
echo anchor(“admin/categories/export”,”Export”);? > < /p >

When you run the test by clicking the Export link, you should see a download dialog appear, as depicted
in Figure 7 - 3.
Free download pdf