
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 🙂
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!
set array to modle es
$data = array {
“placeholder” = “Enter Your Name “,
“Name” = “set name “,
}
Hallo,
where i have to put the code?
Thank you
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
plztel me how to write a code by using codeigniter………
plz tell me
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”)){
}
very nice these code and i,m very appreciate from these
look good