Professional CodeIgniter

(singke) #1

Chapter 7: Improving the Dashboard


227


Notice that color selections are saved in a colors[] array, and size selections are saved in a sizes[]
array. This means that you will need to do an extra bit of processing to update the products_sizes and
products_colors databases.


Open the MProducts model in your editor and find the createProduct() function. What you want to
do right after the insert command (regular text, not bold, below) is to use CodeIgniter to figure out what
the newly created product ’ s ID is. You will need this information in order to properly populate the
mapping tables (products_colors and products_sizes). You can get this ID by using the
$this- > db- > insert_id() function.


Once you have that product ID, you can loop through the colors and sizes and create records in the
products_sizes and products_colors mapping tables.

$this- > db- > insert(‘products’, $data);

$new_product_id = $this- > db- > insert_id();

if (count($_POST[‘colors’])){
foreach ($_POST[‘colors’] as $value){
$data = array(‘product_id’ = > $new_product_id,
’color_id’ = > $value);
$this- > db- > insert(‘products_colors’,$data);
}
}

if (count($_POST[‘sizes’])){
foreach ($_POST[‘sizes’] as $value){
$data = array(‘product_id’ = > $new_product_id,
’size_id’ = > $value);
$this- > db- > insert(‘products_sizes’,$data);
}
}

You ’ re going to want to do all of this in the edit view, with two additions. First, you will need to add two
functions to the MProducts model to extract colors and sizes already assigned to a given product.
These functions should return a list of color and size IDs. You can then check these lists to see if any
checkboxes should be checked.

Here are the functions for the MProducts model. Predictably, they are called getAssignedColors()
and getAssignedSizes().


function getAssignedColors($id){
$data = array();
$this- > db- > select(‘color_id’);
$this- > db- > where(‘product_id’,$id);
$Q = $this- > db- > get(‘products_colors’);
if ($Q- > num_rows() > 0){
foreach ($Q- > result_array() as $row){
$data[] = $row[‘color_id’];
}
}
Free download pdf