CodeIgniter Forms Tutorial

On April 19, 2011, in Articles, CodeIgniter, by Jose

CodeIgniter offers a bunch of helpers to speed up development.  There are URL Helpers, that assist in creating links, there are Form Helpers that help you create form elements, Text Helpers perform various text formatting routines, Cookie Helpers set and read cookies, File Helpers help you deal with files, etc.

As the title implies this tutorial will guide you through the basic usage of one of the most commonly used and valuable helper, the Form Helpers. Part of this forms tutorial is the use of the Form Validation library which has different options for form validation.

 

Setting up the form


By default CodeIgniter does not load any helpers, so the first step should be to load the Form Helper either in your autoload.php file or in the controller you want to use.

apps/main/config/autoload.php

$autoload['helper'] = array('form');

apps/main/controllers/formexample.php

[sourcecode]
$this->load->helper(‘form’);
[/sourcecode]

When loading via the controller always remember to load the form helper first before using any form helper function.

In this forms tutorial will be using most of the Form Helper functions inside our view.

apps/main/controllers/formexample/php

[sourcecode]
function create()
{
$this->load->view(‘formexample/edit’);
}
[/sourcecode]

CodeIgniter forms helper provides various functions to generate different form elements such as form_open(), form_close(), form_label(), form_input(), form_password(), form_radio() and form_checkbox(). These let you create form elements on the fly without going through so much html.

Inside our view let’s create the opening form tag using form_open().

apps/main/views/formexample/edit.php

[sourcecode]
echo form_open($form_action, ”, array (‘submit’ => true));
[/sourcecode]

The first argument is our form’s action, the second would be an array of additional attributes we want to add to the form, and the third is an array of hidden fields we want to create alongside the form.

Adding fields.

Most form helper functions can be used in two ways.

The first method is to pass a field name to the first parameter and a default value (optional) to the second.

echo form_input('user_name', 'john doe');

And the second method is to pass an associative array, which contains the html attributes, to the function.

[sourcecode]
$user_name_attribs = array (
‘name’ => ‘user_name’,
‘id’ => ‘user_name’,
‘value’ => ‘john doe’
);
echo form_input($user_name_attribs);
[/sourcecode]

We’ll use the second method in this forms tutorial. So let’s add it to our edit.php file and some other fields as well.

apps/main/views/formexample/edit.php

[sourcecode]
echo form_open($form_action, ”, array (‘submit’ => true));
$user_name_attribs = array (
‘name’ => ‘user_name’,
‘id’ => ‘user_name’,
‘value’ => ‘john doe’
);
echo form_input($user_name_attribs);
// This creates a password type input field.
echo form_password(‘password’);
// Create the email field.
echo form_input(‘email’);
// Create radio buttons for gender, as with standard html the first parameter
// determines the grouping.
echo form_radio(‘gender’, ’1′, TRUE) . ‘ Male’;
echo form_radio(‘gender’, ’0′) . ‘ Female’;
[/sourcecode]

The form_input() method creates an input field of type text and renders it as html.

Now let’s add a label to the input field we just created using the form_label() method. Just like the form_input() method we can either pass an associative array to the form_label() function, but we’ll keep it simple and pass two parameters, the text we want to display and the name of the field it is for.

[sourcecode]
echo form_label(‘Username:’, ‘user_name’);
[/sourcecode]

Dropdown boxes

When creating a dropdown box we must first define an array which contains the options and their respective values.

[sourcecode]
// This array contains the options for our dropdown.
$dropdown_options = array (
’1′ => ‘Option 1′,
’2′ => ‘Option 2′,
’3′ => ‘Option 3′
);

// Create the dropdown using the options above.
echo form_dropdown(‘options’, $dropdown_options);
[/sourcecode]

Submit button and closing form tag

The submit button is created much like the form_input() method.

[sourcecode]
echo form_submit(‘submit’, ‘Submit’);
[/sourcecode]

Closing the form is as simple as calling the form_close() function.

Now let’s take a look at what we currently have going for edit.php

apps/main/views/formexample/edit.php

[sourcecode]
echo form_open($form_action, ”, array (‘submit’ => true));

// Create an array which contains the html attributes
// we want for the user_name field.
$user_name_attribs = array (
‘name’  => ‘user_name’,
‘id’    => ‘user_name’,
‘value’ => ‘john_doe’
);

// Create our label for user_name.
echo form_label(‘Username:’, ‘user_name’);

// Create the text field using the attributes from the array we created earlier.
echo form_input($user_name_attribs);
// form_error displays the error message after validation.
echo “<br/>”;

// Create the label for the password field.
echo form_label(‘Password:’, ‘password’);

// This creates a password type input field.
echo form_password(‘password’);

echo “<br/>”;

// Create the label for the email field.
echo form_label(‘Email:’, ‘email’);

// Create the email field.
echo form_input(‘email’);

echo “<br/>”;

// Create the label for gender.
echo form_label(‘Gender:’, ‘gender’);

// Create radio buttons for gender, as with standard html the first parameter
// determines the grouping.
echo form_radio(‘gender’, ’1′, TRUE) . ‘ Male’;
echo form_radio(‘gender’, ’0′) . ‘ Female’;

echo “<br/>”;

// This array contains the options for our dropdown.
$dropdown_options = array (
’1′ => ‘Option 1′,
’2′ => ‘Option 2′,
’3′ => ‘Option 3′
);

echo form_label(‘Choose 1:’, ‘options’);

// Create the dropdown using the options above.
echo form_dropdown(‘options’, $dropdown_options);

echo “<br/><br/>”;

echo form_submit(‘submit’, ‘Submit’);

// Close the form.
echo form_close();
[/sourcecode]

Now that we have our form ready, let’s setup form validation and processing.

Form validation and processing


As with any library, we have to load the form_validation helper in order to use it. So on your controller place the following code.

[sourcecode]
$this->load->library(‘form_validation’);
[/sourcecode]

Defining the rules.

The form_validation library provides us with the following set of rules that we can use.

  • required
  • matches
  • min_length
  • max_length
  • exact_length
  • alpha
  • alpha_numeric
  • alpha_dash
  • numeric
  • integer
  • is_natural
  • is_natural_no_zero
  • valid_email
  • valid_emails
  • valid_ip
  • valid_base64

To use these methods we have to call the Form Validation library’s set_rules() function like so.

apps/main/controllers/formexample.php

[sourcecode]
function create()
{
$this->load->library(‘form_validation’);

// Here we tell CodeIgniter about our validation rules.
$this->form_validation->set_rules(‘user_name’, ‘Username’, ‘required’);
$this->form_validation->set_rules(‘password’, ‘Password’, ‘required’);
// We can also use cascading rules like so.
$this->form_validation->set_rules(‘email’, ‘Email’, ‘required|valid_email’);
}
[/sourcecode]

Once we receive a POST request we can call the run() method to start the validation process. This method returns either TRUE or FALSE.

[sourcecode]
if ($this->form_validation->run())
{
// Process the form.
}
[/sourcecode]

Error messages.

We can show validation error messages individually by using the form_error() function. Just pass the field name as a parameter.

apps/main/views/formexample/edit.php

[sourcecode]
echo form_input($user_name_attribs);
// form_error displays the error message after validation.
echo form_error(‘user_name’);
[/sourcecode]

Download the files and test it out.

If you found this article useful, please share your comments below.

5 Responses to CodeIgniter Forms Tutorial

  1. Pradeep says:

    Good article , its really useful………

  2. Shubhzeet says:

    Great tutorial.   best  if more enhanced.  

  3. Cyletech says:

    Thank you for great tutorial.

  4. hujan says:

    how to use radio button in Codeigniter? Been stuck doing radio button for days already.pls help me

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...