Skip to content

Add Edit Views

cannycookie edited this page · 20 revisions
Clone this wiki locally

Category:Help::TipsAndTricks | Category:Help::Views

This page is out of date, the example below does not work.

If you have a standard "CRUD" aspect in your web application, you will probably realise that there is a very fine line between adding and editing. If this is the case, it makes sense to have a single View file that will handle the adding and editing of an item - empty fields when adding and fields populated from the database when editing. This allows you to have a single form which you only need to update once.

How it works

When you call the add or edit/ functions of the controller, the add view is loaded. If you call edit/ however, the information for the item is retrived from the database and also passed to the view.

The view is configured in such a way that it can handle adding and editing of information. It achieves this by checking the values of data that is passed to it, and is helped by a function called field() (listed at the end of this page) which just makes it easier.

Part of the magic is in setting/getting the ID value. The view first checks to see if an ID is present (it will be if you are editing an item). If one is present, the hidden ID field will be set this ID. If, however, no ID is set, the hidden ID field is set to 'X'.

When your form is submitted to save the details, the validation runs, and when successful checks the ID field. If this ID field is X then it calls the model function to insert into the database. Otherwise, it updates the database going by the ID supplied.

Please take a look at the example controller, model and view code below to get a better idea of how this works.



function add(){
  $layout['title'] = 'Add Department';
  $layout['body'] = $this->load->view('departments/departments_add', NULL, True);
  $this->load->view('layout', $layout);

function edit($department_id = NULL){
  // Get ID
  if($department_id == NULL){ $department_id = $this->uri->segment(3); }
  // Load view
  // Get department info by ID
  $body['department'] = $this->department->Get($department_id);
  $layout['title'] = 'Edit Department';
  $layout['body'] = $this->load->view('departments/departments_add', $body, True);
  $this->load->view('layout', $layout);

function save(){

  // Get ID from form
  $department_id = $this->input->post('department_id');

  // Validation rules
  $vrules['department_id'] = 'required';
  $vrules['name'] = 'required|min_length[1]|max_length[50]';

  // Validation fields
  $vfields['department_id'] = 'Department ID';
  $vfields['name'] = 'Name';

  // Set the error delims to a nice styled red hint under the fields
  $this->validation->set_error_delimiters('<p class="hint error"><span>', '</span></p>');

  if ($this->validation->run() == FALSE){

    // Validation failed
    if($department_id != "X"){
      return $this->edit($department_id);
    } else {
      return $this->add();

  } else {

    // Validation succeeded!
    // Create array for database fields & data
    $data = array();
    $data['name'] = $this->input->post('name');
    $data['description'] = $this->input->post('description');

    // Now see if we are editing or adding
    if($department_id == 'X'){
      // No ID, adding new record
    } else {
      // We have an ID, updating existing record
      $this->department->Edit($department_id, $data);

    // Go back to index
    redirect('departments', 'redirect');





function Get($id = NULL){
  // Check if we're getting one row or all records
  if($id != NULL){
    // Getting only ONE row
    $this->db->where('department_id', $id);
    $query = $this->db->get();
    if( $query->num_rows() == 1 ){
      // One row, match!
      return $query->row();        
    } else {
      // None
      return false;
  } else {
    // Get all
    $query = $this->db->get();
    if($query->num_rows() > 0){
      // Got some rows, return as assoc array
      return $query->result();
    } else {
      // No rows
      return false;


function Add($data){
  // Run query to insert blank row
  $this->db->insert('departments', array('department_id' => NULL) );
  // Get id of inserted record
  $id = $this->db->insert_id();
  // Now call the edit function to update the actual data for this new row now we have the ID
  return $this->Edit($id, $data);

function Edit($id, $data){
  $this->db->where('department_id', $id);
  $result = $this->db->update('departments', $data);
  // Return
    return $id;
  } else {
    return false;


  $department_id = @field($this->uri->segment(3, NULL), $this->validation->department_id, 'X');

echo form_open(
  array('class' => 'cssform', 'id' => 'department_add'),
  array('department_id' => $department_id)

<fieldset><legend accesskey="D" tabindex="1">Department Information</legend>
  <label for="name" class="required">Name</label>
    $name = @field($this->validation->name, $department->name);
    echo form_input(array(
        'name' => 'name',
        'id' => 'name',
        'size' => '20',
        'maxlength' => '50',
        'value' => $name,
&lt;?php echo @field($this->validation->name_error) ?&gt;

  <label for="description">Description</label>
    $description = @field($this->validation->description, $department->description);
    echo form_input(array(
        'name' => 'description',
        'id' => 'description',
        'size' => '50',
        'maxlength' => '255',
        'value' => $description,
&lt;?php echo @field($this->validation->description_error) ?&gt;


<div class="submit" style="border-top:0px;">
  &lt;?php echo form_submit(array('value' => 'Save')) ?&gt; 
  &lt;?php echo anchor('departments', 'Cancel') ?&gt;

Field() function - Script


function field($validation, $database = NULL, $last = ''){
  $value = (isset($validation)) ? $validation : ( (isset($database)) ? $database : $last);
  return $value;

Please note that the application/scripts directory functionality has been deprecated. Rather, put the function here: /application/helpers/field_helper.php

then, in your controller do:


===Other Resources about "CRUD"====

Something went wrong with that request. Please try again.