Professional CodeIgniter, Thomas Myer
Chapter 6:                                                                                 Creating a Dashboard        
171
If no POST data are detected, show the form, but along the way, gather up all subcategories eligible for
product assignment with an MCats model function named
getCategoriesDropDown()
 .  You ' ll  build 
this function and the other function you need in a minute. First, here ' s the  
create()
function for your
controller. 
function create(){
  if ($this- 
> 
input- 
> 
post(`name')){
    $this- 
> 
MProducts- 
> 
addProduct();
    $this- 
> 
session- 
> 
set_flashdata(`message','Product created');
    redirect(`admin/products/index','refresh');
  }else{
    $data[`title'] = "Create Product";
    $data[`main'] = `admin_product_create';
    $data[`categories'] = $this- 
> 
MCats- 
> 
getCategoriesDropDown();
    $this- 
> 
load- 
> 
vars($data);
    $this- 
> 
load- 
> 
view(`dashboard');    
  } 
} 
 The   
addProduct()
function in the MProducts model is a little more complicated than the
addCategory()
function you created in the last section, and for one good reason: You have to upload an
image and a thumbnail. 
The first part of the function is extremely straightforward, as you are expecting a series of POST fields
from a form, fields like: name, shortdesc, and so on. These are extremely easy to gather and populate a
data array with:
function addProduct(){
  $data = array( 
  `name' = 
> 
 $_POST[`name'],
  `shortdesc' = 
> 
 $_POST[`shortdesc'],
  `longdesc' = 
> 
 $_POST[`longdesc'],
  `status' = 
> 
 $_POST[`status'],
  `grouping' = 
> 
 $_POST[`grouping'],
  `category_id' = 
> 
 $_POST[`category_id'],
  `featured' = 
> 
 $_POST[`featured'],
  `price' = 
> 
 $_POST[`price']
  ); 
Next, to enable file uploads, you need to do a bit of configuration work. Using a
$config
array, set
values for upload_path (where you expect images to be stored), allowed_types (to restrict the types of 
files that can be uploaded), max_size, and so on, and then load the upload library.
files that can be uploaded), max_size, and so on, and then load the upload library.
Please note that you must set the upload_path folder to be writable for any of this to work! Checking on
that and making sure it is writable will save you a lot of time.
c06.indd   171
c06.indd   171
6/10/08   5:36:05 PM
6/10/08   5:36:05 PM