• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / How To Work With CodeIgniter Forms

How To Work With CodeIgniter Forms

March 28, 2013 by Rana Ahsan 8 Comments

codeigniter forms tutorial

For a web application, HTML forms are the probably most important sections. Because, these are the real interface which make it happen to communicate and receives/store data from visitors. Now a days, we can’t even imagine a website without at least a contact form or so. As always, codeigniter framework have done an incredible job by providing integrated supports to deal with these forms. Basically, codeigniter support for forms has two sections. A library class, known ‘codeigniter forms validation class’. Another is form helper, which is a set of functions to provide easy way to render HTML forms input controls.

What We Will Learn Today:

Today, in this tutorial, we will learn:

  • How to create form validation rule
  • Render a form with codeigniter form helper And
  • Process submitted data

As Example, We will consider a traditional contact form to illustrate these.

Create Validation Rule Set:

There are two ways to define rules for a form. You can either have it predefined in a config file. Otherwise, you can define the rules dynamically inside the controller function as well. First is better if you wish to reuse the configuration on different pages/controller functions.

Here is an example rule definition in config:

$config['contact_rules'] =  array(
           'name' => array(
                     'field' => 'name',
                     'label' => 'Name',
                     'rules' => 'trim|required|xss_clean'
                     ),
           'email' => array(
                     'field' => 'email',
                     'label' => 'Email',
                     'rules' => 'trim|required|valid_email'
                     ),
           'subject' => array(
                     'field' => 'subject',
                     'label' => 'Subject',
                     'rules' => 'trim|required|xss_clean'
                     ),
           'message' => array(
                      'field' => 'message',
                      'label' => 'Message',
                      'rules' => 'trim|required|xss_clean'
                      )
           );

As you can see on above code, the codeigniter forms configuration is a two-dimensional key/value pair based array. Where, first dimension defines fields and second dimension defines three different property of each item:

  • field: Defines that name attribute of that particular field.
  • label: Defines the label text for that field.
  • rules: Defines the criteria that filed need to be fulfilled. Such as ‘required’ tells the codeigniter form validation class that this field can’t be empty. ‘valid_email’ rule tells to validate the submitted input to a valid email format. ‘trim’ rule actually doesn’t validate anything, rather it just perform an action of trim operation on the submitted input. Similarly, ‘xss_clean’ rule make sure and process input to become safe from security vulnerability.

As an alternative, we can define the rules dynamically in controller function as below:

$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('subject', 'Subject', 'trim|required|xss_clean');
$this->form_validation->set_rules('message', 'message', 'trim|required|xss_clean');

Read The Complete CodeIgniter Tutorials Series By CodeSamplez.com

Initial Controller Function To Load Rules And Views:

Here is a simple contact controller function that loads the rules and pass them to view.

    /**
     * Controller For 'Contact Page'
     */
    public function contact()
    {
        try
        {
            $data["contact_form"] = $this->config->item("contact_rules");

            return $this->load->view("contact",$data["contact_form"]);
        }
        catch(Exception $err)
        {
            log_message("error", $err->getMessage());
            return show_error($err->getMessage());
        }
    }

Well, we are gonna change it soon as the submitted data will be processed in this same function. Keep reading 🙂

View For Our CodeIgniter Form:

Lets see now how we can utilize the codeiniter forms helper. Following is a very simple illustration of the contact form in codeigniter way:

echo form_open('', '');

echo form_label($contact_form["name"]["label"], $contact_form["name"]["field"]);
echo form_input($contact_form["name"]["field"], '');

echo form_label($contact_form["email"]["label"], $contact_form["email"]["field"]);
echo form_input($contact_form["email"]["field"], '');

echo form_label($contact_form["subject"]["label"], $contact_form["subject"]["field"]);
echo form_input($contact_form["subject"]["field"], '');

echo form_label($contact_form["message"]["label"], $contact_form["message"]["field"]);
echo form_input($contact_form["message"]["field"], '');

echo form_submit('submit', 'Submit');
echo form_close();

However, many developers, including myself, don’t like to write php code in the view part and thus use third-party php template engine, such as smarty. Following is the smarty way to render the view. This is basically become helpful for web designers to see the view on IDE properly:

<div class="span4" id="error">
        <form name="contact" method="post" action="{$base_url}home/contact" id="contact" class="well">            
            <fieldset>
                <legend>Contact</legend> 
                <label class="control-label" for="name">{$contact_form.name.label} :</label>
                <input type="text" name="{$contact_form.name.field}" id="name" class="required">

                <label class="control-label" for="email">{$contact_form.email.label} :</label>
                <input type="text" name="{$contact_form.email.field}" id="email" class="required email">

                <label class="control-label" for="subject">{$contact_form.subject.label} :</label>
                <input type="text" name="{$contact_form.subject.field}" id="subject" class="required">

                <label class="control-label" for="message">{$contact_form.message.label} :</label>
                <textarea name="{$contact_form.message.field}" id="message" cols="45" rows="3" class="required"></textarea>

                <input type="submit" name="submit" id="submit" value="Submit" class="btn">
            </fieldset>
        </form>

The choice is totally up to you how you want to get your views organized. End result is same. Lets move ahead process the submitted form.

Validate The Form After Submission:

After user submits a form, we first need to make sure, the data in valid according to our defined rules. So, here you go:

//inside the contact function, just before loading the view
if($this->input->post('submit')){
                
   $this->load->library("formvalidator");
   if($this->formvalidator->isValid("contact")){
                    
      //process data
      }
      else{
         //show validation error
         $this->data["status"]->message = validation_errors();
         $this->data["status"]->success = FALSE;
      }
   }

As you can see, here we used another library named ‘formvalidator’, which I suggest to use and it is as follows:

<?php
/**
 * Description of FormValidator
 *
 * @author Rana
 */
class Formvalidator {
    //put your code here

    function __construct() {
        $this->ci =& get_instance();
    }
    
    /**
     * Determin whether a submitted form is valid or not according to given rule on config file
     * @param String $form_name
     * @return boolean 
     */
    function isValid($form){
        $this->ci->load->library('Form_validation');
        $this->ci->load->helper('form');
        $this->ci->form_validation->set_rules($form);
        
        if($this->ci->form_validation->run()){
            return true;
        }
        else{
            return false;
        }
        
    }
}

This can be a common small library that you can call from anywhere from your application and thus saves couple lines of code duplication. Please let me know your suggestions to improve it if you have any.

Process Submitted Data:

Now, as we have validated the form, we can process the submitted data easily. Just only one thing to remember here, instead of using php core “$_POST”,”$_GET” or “$_REQUEST” variables, lets use “$this->input->get()” or “$this->input->post()” methods, because these functions do the basic security check on the data and removes the need of checking “isset($_POST[‘name’])” type checking, which simplifies the code in a descent way:

        $contact = new Message();
        $contact->name = $input->post($contact_form["name"]["field"]);
        $contact->email = $input->post($contact_form["email"]["field"]);
        $contact->subject = $input->post($contact_form["subject"]["field"]);
        $contact->message = $input->post($contact_form["message"]["field"]);
        $contact->time = new DateTime();
        //save the object to database 

And we can now move ahead to use the data to save into database using codeigniter active record class or using doctrine with codeigniter, whatever you prefer.

Final Words:

You should read the official documentation of validation library and forms helper by codeigniter. If you are having any kind of issue in this tutorial, please let me know. I will try my best to get back to you as soon as I can. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: codeigniter, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. luislobo says

    August 26, 2013 at 6:04 am

    Hi, Thank you for your article. I have two questions:
    1) does your code handles reloading posted values after validation? It doesn’t seem to. How would you do it?
    2) What if you add a field that is optional? I mean, you don’t want to validate anything. You add it with no “rules”? Or is there a “placeholder” rule?

    Thank you!

    Reply
    • Malik Ahmad says

      February 15, 2015 at 6:22 am

      set array to modle es

      $data = array {

      “placeholder” = “Enter Your Name “,
      “Name” = “set name “,

      }

      Reply
  2. Wiyono says

    January 11, 2014 at 10:05 pm

    Hallo,
    where i have to put the code?

    Thank you

    Reply
  3. andymnc says

    January 14, 2014 at 7:38 pm

    it’s not clear to me too, so far.
    also, can you give an example about using
    $this->form_validation->set_rules….
    in your example you use:
    $data[“contact_form”] = $this->config->item(“contact_rules”);
    return $this->load->view(“contact”,$data[“contact_form”]);
    but if i am not using it and i am setting the rules dynamically, how can i do?
    thanks in advance

    Reply
  4. deva says

    August 26, 2014 at 5:29 am

    plztel me how to write a code by using codeigniter………
    plz tell me

    Reply
  5. swati says

    April 14, 2015 at 1:53 pm

    config->load(‘config_login’);
    $this->output->enable_profiler(TRUE);

    }

    public function index() {

    }

    public function login()
    {
    try
    {
    //Fetching Config Items
    $data[“login_form”] = $this->config->item(“login_rules”);

    // print_r($data[“login_form”]);

    //inside the login function, just before loading the view
    if($this->input->post(‘submit’)){

    $this->load->library(“login_validation”);
    if($this->login_validation->isValid(“login”)){

    //process data
    }
    else{
    //show validation error
    $this->data[“status”]->message = validation_errors();
    $this->data[“status”]->success = FALSE;
    }
    }

    return $this->load->view(“admin/admin_login_form”,$data[“login_form”]);
    }
    catch(Exception $err)
    {
    log_message(“error”, $err->getMessage());
    return show_error($err->getMessage());
    }
    }

    }

    I cannot understand what to pass here -> isValid(” “)) ?

    if($this->login_validation->isValid(“login”)){
    }

    Reply
  6. Tariq shah says

    September 14, 2015 at 2:48 am

    very nice these code and i,m very appreciate from these

    Reply
  7. musheer says

    September 15, 2015 at 5:08 am

    look good

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023