Professional CodeIgniter

(singke) #1

Chapter 6: Creating a Dashboard


166


Notice that the category ID is passed to the function as an argument. Also notice that its default state is 0.
Why? Because this function does double duty, sometimes working off a URI segment and sometimes
working from POST data. Since you ’ ve already built the getTopCategories() and getCategory()
functions, there ’ s nothing to do there. All you have to do is add an updateCategory() function to the
MCats model.

In form and function, this function is very similar to the previous addCategory() function, except for
the last two lines, where you set a where clause (limiting the forthcoming update to a certain category
ID) and use $this- > db- > update() instead of $this- > db- > insert().

function updateCategory(){
$data = array(
‘name’ = > $_POST[‘name’],
‘shortdesc’ = > $_POST[‘shortdesc’],
‘longdesc’ = > $_POST[‘longdesc’],
‘status’ = > $_POST[‘status’],
‘parentid’ = > $_POST[‘parentid’]

);

$this- > db- > where(‘id’, $_POST[‘id’]);
$this- > db- > update(‘categories’, $data);

}

Next, build the Edit form. All you really have to do is use the Create form as your model, but remember
that you have to make three small changes. First, make sure it posts to the admin/categories/edit path.
Second, make sure that you embed a hidden field with the category ID in it to make updateCategory()
work right. Third, make sure that you load all the data from $category into the form fields.

< h1 > < ?php echo $title;? > < /h1 >

< ?php
echo form_open(‘admin/categories/edit’);
echo “ < p > < label for=’catname’ > Name < /label > < br/ > ”;
$data = array(‘name’= > ’name’,’id’= > ’catname’,’size’= > 25, ‘value’ = >
$category[‘name’]);
echo form_input($data) .” < /p > ”;

echo “ < p > < label for=’short’ > Short Description < /label > < br/ > ”;
$data = array(‘name’= > ’shortdesc’,’id’= > ’short’,’size’= > 40, ‘value’ = >
$category[‘shortdesc’]);
echo form_input($data) .” < /p > ”;

echo “ < p > < label for=’long’ > Long Description < /label > < br/ > ”;
$data = array(‘name’= > ’longdesc’,’id’= > ’long’,’rows’= > 5, ‘cols’= > ’40’, ‘value’ = >
$category[‘longdesc’]);
echo form_textarea($data) .” < /p > ”;

echo “ < p > < label for=’status’ > Status < /label > < br/ > ”;
$options = array(‘active’ = > ‘active’, ‘inactive’ = > ‘inactive’);
echo form_dropdown(‘status’,$options, $category[‘status’]) .” < /p > ”;
Free download pdf