1
\$\begingroup\$

I'm working with Codeigniter most of the time (about one and a half year now) and I came across many form validation code flows. Here are my best two selected shots which I created for a client recently.

I only care about model and controller, views do not need to be reviewed.

Features of both code:

  • Validation for form components with rules
  • Show what error is in form field
  • Get previous filled data when validation do not satisfy

Code 1:

Controller:

public function add()
{
    $this->input->post() and $this->jobs->insert() and redirect('jobs');

    $data['jobs'] = $this->jobs;
    $data['errors'] = validation_errors();

    $this->load->view('main_header');
    $this->load->view('jobs_edit', $data);
    $this->load->view('main_footer');       
}
public function edit($id=0)
{
    $this->input->post() and $this->jobs->update() and redirect('jobs');

    ctype_digit($id) or redirect('jobs');

    $get_one = $this->db->get_where('job', array('id'=>$id))->row();
    $get_one or redirect('jobs');

    $this->input->post() or $this->jobs->get_current();

    $data['jobs'] = $this->jobs;
    $data['errors'] = validation_errors();

    $this->load->view('main_header');
    $this->load->view('jobs_edit', $data);
    $this->load->view('main_footer');
}

Model:

class Jobs_model extends CI_Model {

    public $id;
    public $emp_id;
    public $company;
    public $job_title;
    public $job_description;
    public $location;
    public $skill;
    public $industry;
    public $interview_date;
    public $salary_from;
    public $salary_to;
    public $finders_fee_from;
    public $finders_fee_to;
    public $created_at;

    public function __construct()
    {
        $this->set_segment();
        $this->set_post();
    }
    public function set_post()
    {
        foreach($this->input->post() as $k => $v)
            $this->$k = $v;
    }

    function set_segment()
    {
        $id = $this->uri->segment(3,0);
        ctype_digit($id) and $this->id=$id;
    }

    function get_current()
    {
        $result = $this->db->get_where('job', array('id'=>$this->id))->row();
        foreach($result as $k => $v)
            $this->$k = $v;
    }

    function get_all()
    {
        return $this->db->from('job')->get()->result();
    }

    function insert()
    {
        $this->set_rules();
        if($this->form_validation->run() == false)
            return false;
        $insert = array(
                'emp_id' => $this->emp_id,
                'company' => $this->company,
                'job_title' => $this->job_title,
                'job_description' => $this->job_description,
                'location' => $this->location,
                'skill' => $this->skill,
                'industry' => $this->industry,
                'interview_date' => date('Y-m-d H:i:s', strtotime($this->interview_date)),
                'salary_from' => $this->salary_from,
                'salary_to' => $this->salary_to,
                'finders_fee_from' => $this->finders_fee_from,
                'finders_fee_to' => $this->finders_fee_to,
                'created_at' => date('Y-m-d H:i:s'),
            );
        $this->db->insert('job', $insert);
        $this->session->set_flashdata('msg','Record added successfully!');
        return true;
    }

    function update()
    {
        $this->set_rules();
        if($this->form_validation->run() == false)
            return false;
        $update = array(
                'emp_id' => $this->emp_id,
                'company' => $this->company,
                'job_title' => $this->job_title,
                'job_description' => $this->job_description,
                'location' => $this->location,
                'skill' => $this->skill,
                'industry' => $this->industry,
                'interview_date' => date('Y-m-d H:i:s', strtotime($this->interview_date)),
                'salary_from' => $this->salary_from,
                'salary_to' => $this->salary_to,
                'finders_fee_from' => $this->finders_fee_from,
                'finders_fee_to' => $this->finders_fee_to,
            );
        $this->db->update('job', $update, array('id' => $this->id));
        $this->session->set_flashdata('msg','Record updated successfully!');
        return true;
    }

    function set_rules()
    {
        $this->form_validation->set_rules('company', 'Company name', 'trim|required|min_length[3]');
        $this->form_validation->set_rules('job_title', 'Job title', 'trim|required|min_length[3]');
        $this->form_validation->set_rules('location', 'Location', 'trim|required|min_length[3]');
        $this->form_validation->set_rules('salary_from', 'Salary from', 'trim|required|integer');
        $this->form_validation->set_rules('salary_to', 'Salary to', 'trim|required|integer');
        $this->form_validation->set_rules('finders_fee_from', 'Finders fee from', 'trim|required|integer');
        $this->form_validation->set_rules('finders_fee_to', 'Finders fee to', 'trim|required|integer');
    }
}

Code 2:

Controller:

public function add()
{
    $data = array('page_title' => 'Add City - Viral Vadgama');
    $data['city_name'] = '';
    $data['state_id'] = '';
    $data['country_id'] = '';

    if($this->input->post())
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('city_name', 'City Name', 'required|min_length[3]');
        $this->form_validation->set_rules('country_id', 'Country', 'required');
        $this->form_validation->set_rules('state_id', 'State', 'required');

        if($this->form_validation->run() !== FALSE)
        {
            $insert_id = $this->city_model->insert_city(
                            $this->input->post('city_name'),
                            $this->input->post('state_id')
                        );
            $this->session->set_flashdata('data','City added successfully with ID:'.$insert_id);
            redirect('city');
        }
        else
        {
            $data['city_name'] = $this->input->post('city_name');
            $data['state_id'] = $this->input->post('state_id');
            $data['country_id'] = $this->input->post('country_id');
        }
    }

    $this->load->view('templates/header', $data);
    $this->load->view('city/add', $data);
    $this->load->view('templates/footer', $data);
}

public function edit($id=0)
{
    $data = array('page_title' => 'Edit City - Viral Vadgama');
    if(!ctype_digit($id)) redirect('city');
    $current = $this->city_model->get_cities($id);
    if(!$current) redirect('city');
    $data['city_name'] = $current->city_name;
    $data['state_id'] = $current->state_id;
    $data['country_id'] = $current->country_id;
    $data['id'] = $id;

    if($this->input->post())
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('city_name', 'City Name', 'required|min_length[3]');
        $this->form_validation->set_rules('country_id', 'Country', 'required');
        $this->form_validation->set_rules('state_id', 'State', 'required');
        if($this->form_validation->run() !== FALSE)
        {
            $insert_id = $this->city_model->edit_city(
                            $this->input->post('city_name'),
                            $this->input->post('state_id'),
                            $id
                        );
            $this->session->set_flashdata('data','City edited successfully with ID:'.$id);
            redirect('city');
        }
        else
        {
            $data['city_name'] = $this->input->post('city_name');
            $data['state_id'] = $this->input->post('state_id');
            $data['country_id'] = $this->input->post('country_id');
        }
    }

    $this->load->view('templates/header', $data);
    $this->load->view('city/edit', $data);
    $this->load->view('templates/footer', $data);
}

Model:

class City_model extends CI_Model {

    function __construct()
    {
        parent::__construct();
    }

    function get_cities($id=0)
    {
        $this->db->select('ci.id as city_id, ci.name as city_name, ci.state_id as state_id,
                            s.name as state_name, s.id as state_id, s.country_id as country_id,
                            c.name as country_name, c.iso2 as iso2');
        $this->db->from('cities ci');
        $this->db->join('states s', 's.id=ci.state_id', 'left');
        $this->db->join('countries c', 's.country_id=c.id', 'left');

        if($id)
        {
            $this->db->where('ci.id', $id);
            return $this->db->get()->row();
        }

        $this->db->order_by('ci.id');
        return $this->db->get()->result();
    }

    function delete_city($id=0)
    {
        $this->db->where('id', $id);
        $this->db->delete('cities');
        return $this->db->affected_rows();
    }

    function insert_city($name='', $state_id='')
    {
        $data = array(
            'name' => $name,
            'state_id' => $state_id
        );
        $this->db->insert('cities', $data);
        return $this->db->insert_id();
    }

    function edit_city($name='', $state_id='', $id=0)
    {
        $data = array(
            'name' => $name,
            'state_id' => $state_id
        );
        $this->db->where('id', $id);
        $this->db->update('cities', $data);

        return $this->db->affected_rows();
    }
}

Both code snippets work perfectly as they should, but code 1 is for another SQL table, so variables will be different but both do the same thing.

Which is the best of the two codes to use ? or any improvements in any code.

Here is the full code if want to take a look at that:

Code in action:

Code 2

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.