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.
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:
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:
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
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?
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
var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("%7B%22overlayOptions%22%3A%7B%22colorTheme%22%3A%22light%22%2C%22enableInfScroll%22%3Atrue%2C%22enableFilteringOpensOverlay%22%3Atrue%2C%22enablePostDate%22%3Atrue%2C%22enableSort%22%3Atrue%2C%22highlightColor%22%3A%22%23FFC%22%2C%22overlayTrigger%22%3A%22submit%22%2C%22resultFormat%22%3A%22expanded%22%2C%22showPoweredBy%22%3Atrue%2C%22defaultSort%22%3A%22relevance%22%2C%22excludedPostTypes%22%3A%5B%5D%7D%2C%22homeUrl%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%22%2C%22locale%22%3A%22en-US%22%2C%22postsPerPage%22%3A5%2C%22siteId%22%3A18994550%2C%22postTypes%22%3A%7B%22post%22%3A%7B%22singular_name%22%3A%22Post%22%2C%22name%22%3A%22Posts%22%7D%2C%22page%22%3A%7B%22singular_name%22%3A%22Page%22%2C%22name%22%3A%22Pages%22%7D%2C%22attachment%22%3A%7B%22singular_name%22%3A%22Media%22%2C%22name%22%3A%22Media%22%7D%7D%2C%22webpackPublicPath%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-content%5C%2Fplugins%5C%2Fjetpack%5C%2Fjetpack_vendor%5C%2Fautomattic%5C%2Fjetpack-search%5C%2Fbuild%5C%2Finstant-search%5C%2F%22%2C%22isPhotonEnabled%22%3Afalse%2C%22isFreePlan%22%3Atrue%2C%22apiRoot%22%3A%22https%3A%5C%2F%5C%2Fcodesamplez.com%5C%2Fwp-json%5C%2F%22%2C%22apiNonce%22%3A%22155bc22a78%22%2C%22isPrivateSite%22%3Afalse%2C%22isWpcom%22%3Afalse%2C%22hasOverlayWidgets%22%3Afalse%2C%22widgets%22%3A%5B%5D%2C%22widgetsOutsideOverlay%22%3A%5B%5D%2C%22hasNonSearchWidgets%22%3Afalse%2C%22preventTrackingCookiesReset%22%3Afalse%7D"));
luislobo says
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!
Malik Ahmad says
set array to modle es
$data = array {
“placeholder” = “Enter Your Name “,
“Name” = “set name “,
}
Wiyono says
Hallo,
where i have to put the code?
Thank you
andymnc says
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
deva says
plztel me how to write a code by using codeigniter………
plz tell me
swati says
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”)){
}
Tariq shah says
very nice these code and i,m very appreciate from these
musheer says
look good