The official CodeIgniter documentation contains a useful tutorial on how to use CodeIgniter to create a news section on a website. Unfortunately the tutorial only shows you how to list news, view individual news posts and create new news posts. In this tutorial I will be showing how to extend this code to include the ability to edit news. I’m assuming you are using CodeIgniter 2.1 and have followed the tutorials for static pages, news section and create news items.

Model – news_model.php

Updates to the news model are pretty straight forward, we take the set_news() method and duplicate it. We need to know which article is being edited so we pass through the ID. This is then used with the CI database class to add a WHERE clause to the SQL before sending the UPDATE query to the database.

/**
* Updates news in to DB
*
* @access public
* @param int
* @return bool
*/
public function update_news($id=0)
{
	$this->load->helper('url');
 
	$slug = url_title($this->input->post('title'),'dash',TRUE);
 
	$data = array(
		'title'	=>	$this->input->post('title'),
		'slug'	=>	$slug,
		'text'	=>	$this->input->post('text')
	);
	$this->db->where('id',$id);
	return $this->db->update('news',$data);
}

View – /news/view.php

A simple update, we add an edit link to the single news article view;

<p><a href="/news/update/{id}">Edit</a></p>

You’ll notice that this code makes use of the CodeIgniter template parser class, if you aren’t using the template parser then your revised code will look something similar to this;

<p><a href="/news/update/<?php echo $news_item['id'] ?>">Edit</a></p>

View – /news/update.php

Now we create our new view for editing the news article in. This is a copy of the create.php file you would have created in the official tutorial. Notice that I am not using the template parser class in this file, there is no reason not to use the parser so feel free to update your code.

The main difference between this view and the create view is we will at some point pass a flag back to display a success message to the user.

<h2>Edit a news item</h2>
<?php echo validation_errors(); ?>
<?php if ($success){?>
<h3>News successfully updated</h3>
<?php } ?>
<?php echo form_open('news/update/'.$news_item['id']) ?>
    <label for="title">Title</label>
    <input type="input" name="title" value="<?php echo $news_item['title'];?>" /><br />
 
    <label for="text">Text</label>
    <textarea name="text"><?php echo $news_item['text'];?></textarea><br />
 
    <input type="submit" name="submit" value="Update news item" />
    </form>

Controller – news.php

We now need to add an update method to our news controller. This is based off of the create method.

First we validate the form, if it’s successful we call the update_news method from the news model, the result is assigned to the success key in the data array before we pass the array to the update view. If you remember we added some logic to the update view that is triggered if successful.

public function update($id)
{
    $data['title'] = 'Edit a news item';
    $data['success'] = 0;
 
    $this->load->helper('form');
    $this->load->library('form_validation');
 
    $this->form_validation->set_rules('title','Title','required');
    $this->form_validation->set_rules('text','text','required');
 
    if($this->form_validation->run())
    {
        $data['success'] = $this->news_model->update_news($id);
    }
 
    $data['news_item'] = $this->news_model->get_news($id);
    if(empty($data['news_item']))
    {
        show_404();
    }
 
    $this->load->view('templates/header',$data);
    $this->load->view('news/update',$data);
    $this->load->view('templates/footer');
}

Updating routes.php

Finally we need to update the CodeIgniter routing file found in the config folder. This should currently look like the following;

$route['news/create'] = 'news/create';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
$route['404_override'] = '';

We need to add a new route below the “create” route to get access the new edit functionality we’ve added;

$route['news/update/(:any)'] = 'news/update/$1';

Fin

So there we go, our CodeIgniter news section has now gained the ability to edit news articles.

Tagged with:
  • nick

    i have followed your instructions and i get page not found error :(
    i have copied and pasted and checked but still its not working.

    • Albo

      Hi Nick, which page is 404ing?

      • Matt

        /news/update

        There’s confusion with the $id – something missing from your code, or your code from the original tutorial has been modified?

        Massive beginner at this, but after an hour of poking about with the code, I can get it to work (more or less) if I replace id with slug.

  • Matt

    That’ll be the news/update page.

    Being a neophyte at this, still haven’t found a fix.
    Your code above needs index.php in the edit link, most likely you’ve got an .htaccess setup which removes that.

    The error lies in the routes I think…

    • Albo

      Hi Matt, I may have removed the index.php (Sorry I no longer have the source files, bad that I am – I did this as part of learning CI so I’m by no means an expert!) as per this page; http://codeigniter.com/user_guide/general/urls.html Let me know how you get on, if it’s still not working I’ll setup CI again and run some tests!

  • Rahul Yadav

    There are some bugs in this code w.r.t to newbies like me. The tutorial is helpful but few edits are required to make it work perfectly. In the controller news.php the method get_news($id) called from model is the first issue. There is no method in the model corresponding to this signature(i.e we have only get_news() function). So rather than updating individual news section by id, we can update them using slug. So replace all occurrences of “id” by “slug” and you will be able to update your individual news section.
    Hope this helps :)