O'Reilly logo

Professional CodeIgniter® by Thomas Myer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.4. Reassigning Products from Deleted Categories

Now that you've met with Claudia, you know how she wants to handle potentially orphaned products. Orphaned products come about as a natural result of deleting a "container" like a category. If the category goes away, what do you do with all the items that it is "holding"? Now that you know what Claudia's expectations are, it's an easy matter of adding a bit of processing to the end of the admin/categories/delete function.

Here's a quick look at that function to refresh your memory:

function delete($id){
  $this->MCats->deleteCategory($id);
  $this->session->set_flashdata('message','Category deleted');
  redirect('admin/categories/index','refresh');
}

What you're going to need when you rewrite this function is some way to check for orphaned products. The best way to do that is to create a checkOrphans() function in the MCats model. This function accepts a category ID as its only argument and then returns an array of products that match that category_id.

function checkOrphans($id){
  $data = array();
  $this->db->select('id,name');
  $this->db->where('category_id',$id);
  $Q = $this->db->get('products');
    if ($Q->num_rows() > 0){
      foreach ($Q->result_array() as $row){
        $data[$row['id']] = $row['name'];
      }
    }
  $Q->free_result();
  return $data;
}

Now that you have this function in place, you can rewrite the delete() controller function.

function delete($id){ $this->MCats->deleteCategory($id); $orphans = $this->MCats->checkOrphans($id); if (count($orphans)){ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required