Introduction to Code Igniter: Part 2

12 comments | Posted: 18 July 06 in Tutorials, by Yannick Lyn Fatt

Please note the following tutorial was done using an older version of CodeIgniter. As such, somethings may not work properly in more recent versions of the framework. Please visit the CodeIgniter website and download version 1.3.3 or 1.4.1, if you would like to run this tutorial in it's original form. For Updated code please download "intro-to-codeigniter-code.zip":http://godbit.com/files/intro-to-codeigniter-code.zip


In Part 1 of this introduction to the PHP framework Code Igniter we went through a few of the basics of CI. We created our first controller, a view and went into some of the form functions that are available in our form helper. In this installment I've decided to focus on being able to extend the functionality of the registration form we created in Part 1 by having it send the completed form data to an e-mail address using CI's E-mail class and also put some validation in place using CI's Validation class so that certain fields are required are filled in properly. I know your itching to get started so let's go!

A slight fix

While working on part 2 I realised I had made a slight error when I was creating the checkboxes for the registration form. Since we are using checkboxes we are allowing the participant to select more than one seminar, therefore we need to have the name attribute like this name="seminar[]" instead of name="seminar". This will allow PHP to store all the selected seminars in an array. Also I forgot to add values to the checkboxes. This is important as when we are sending the e-mail (and later adding to a database) we would like actually see the name of the seminars chosen to be listed. So this is how your controller should now look:


function index()
{
#Input and textarea field attributes
$data["fname"] = array('name' => 'fname', 'id' => 'fname');
$data['email'] = array('name' => 'email', 'id' => 'email');
$data['comments'] = array('name' => 'comments', 'id' => 'comments', 'rows' => 3, 'cols' => 40);

#Checkbox attributes
$data['purpose'] = array('name' => 'seminar[]', 'id' => 'purpose', 'value' => 'Purpose of Prayer', 'checked' => FALSE);
$data['prepare'] = array('name' => 'seminar[]', 'id' => 'prepare', 'value' => 'Prepare for Prayer', 'checked' => FALSE);
$data['principles'] = array('name' => 'seminar[]', 'id' => 'principles', 'value' => 'Principles of Prayer', 'checked' => FALSE);
$data['power'] = array('name' => 'seminar[]', 'id' => 'power', 'value' => 'Power in Prayer', 'checked' => FALSE);

#Load our view	
$this->load->view('form_view', $data);
}

Note: This has also been updated in the file from the previous tutorial so feel free to re-download it before proceeding or make the above changes to your files yourself.

Now back to the show

With that small error now fixed lets get crackin'. You might remember from Part 1 that we had told CI to autoload our E-mail class. We didn't actually have to do it that way. In fact since we are only using the e-mail class when we submit the form we could have just as easily loaded it in the function that deals with form submission. In cases like that you use the following:

$this->load->library('email');

If however you are going to be using a particular script, library or helper frequently in your application then it would be best to autoload it. For the sake of this tutorial I will leave it autoloaded.

Before we go any further we have to make another minor change to ensure that our e-mails will be sent. If you have access to your php.ini file then open it up and look for the section that says [mail function]. If you are using Windows (like I am) then make changes to the following lines:

SMTP = mail.yourmailserver.com

and

sendmail_from = whatever@yourmailserver.com

As for users of Linux and Mac, I think, though I'm not 100% sure, you will need to make a change to the line just below those two:

sendmail_path =

Ensure that you remove the semicolon (;) before any of those lines that you have changed. The semicolon reperesents a comment in the php.ini file. Save the changes you just made to the php.ini file.

Now with all of that technical mumbo jumbo out of the way, let's create our submit function that deals with sending the e-mail. It will look something like this:


function submit()
{ 
  #Get POST data
  $fname = $this->input->post('fname');
  $email = $this->input->post('email');
  $comments = $this->input->post('comments');
  $seminars = "";
	
  foreach($this->input->post('seminar') as $value){
	  $seminars .= "$value\n";
  }	

  $message = $fname . " would like to register for the following   seminars\n" . $seminars;

  #Set our e-mail fields
  $this->email->from($email, $fname);
  $this->email->to('john.doe@welovejesus.com');
  $this->email->subject('Seminar Registration');
  $this->email->message($message);
  $this->email->send();
  #load our view file
  $this->load->view('formsuccess');
}
 
 

Pretty simple right? Yup it's just that simple. And in fact most of it is pretty self explanatory, but I will still go through it anyway.

$fname = $this->input->post('fname');

This is doing basically the same thing that $fname = $_POST['fname'] would be doing except it checks to see if the item is set and returns false if not.

$this->email->from($email, $fname);

takes in two parameters. The first is the e-mail address of the sender and the second is the name of the sender.

$this->email->to('john.doe@welovejesus.com');

will send the e-mail to the specified address. This of course will be changed to your e-mail address or whoever will be receiving the participants submitted data.

$this->email->subject('Seminar Registration');

is the subject of the e-mail to be sent.

$this->email->message($message);

is the message body of the e-mail which we specified in our $message variable.

$this->email->send();

basically gives the go ahead to send the e-mail.

Now we are going to create our view called formsuccess.php which will be displayed when the e-mail has been sent so that we know everything went through okay. Here is the code:


 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html>
 <head>
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>Godbit Code Igniter Tutorial: Creating a simple Registration Form</title>
 </head>
 <body>
  <h1>Registration Form Completed</h1>
  <p>Your registration form has been successfully submitted.</p>
 </body>
 </html>
 
 

Note: Take out the spaces between the opening "<" and the element name.

Save that file in your views folder. Now open your browser and fill out the registration form at http://localhost/regform/index.php/form . After hitting the submit button you should see your success page. Check your e-mail and you should see the submitted data.

That's all good and well but what if we wanted to ensure that certain fields were filled out? CI comes with validation support built right in. Next we'll validate some of our form fields.

Validations

Validating form data is one of those things that no one really likes to do, but it has to be done. With CI that task is a bit easier to do with it's built in Validation class. Let us first add the following to our controller in the index() function:


#Validations
$this->load->library('validation');
$rules['fname'] = "required";
$rules['email'] = "required|valid_email";
$this->validation->set_rules($rules);
 

We have first loaded the validation class and then we have set the rules we would like it to check for. The required rule simply checks to ensure that the fname input field is filled in. While the valid_email rule, ensures that a valid e-mail address (with the @ sign) is entered.

Previously we had declared the view for the current function, like so:

$this->load->view('form_view', $data);

We will change that instead to the following:


if ($this->validation->run() == FALSE)
{
  $this->load->view('form_view', $data);
}
else
{
  $this->load->view('formsuccess');
}

What this does is that if there is a validation error, it will reload the form, so that the user can correct that error, else it will display our success page. Now let us make a few changes to our view. Change:

echo form_open('form/submit'); 

to

echo form_open('form/index'); 

What that does is that on submission it will submit the form data to itself (ie. the index() function in our controller) where it can do the necessary validation checks as specified by the rules in our index() function. Also, just above our form_open() function in our view we will add the following:

echo $this->validation->error_string; 

This is responsible for displaying our error message, so the user knows where they went wrong. With all that done give the form a try without filling in the fname and/or email input fields. Also try putting in an e-mail address without the "@" symbol. Once you are satisfied fill out the form correctly and submit. It works but wait, it didn't send the e-mail. The answer to why it didn't send the e-mail lies in the fact that when all requried fields are filled out the form data is no longer passed to the submit() function in our controller and is essentially just displaying the success page only. To solve that it's simply a matter of copying the code we had in our submit() function and pasting it in the else statement in our index() function.


if ($this->validation->run() == FALSE)
{
  $this->load->view('form_view', $data);
}
else
{
  $fname = $this->input->post('fname');
  $email = $this->input->post('email');
  $comments = $this->input->post('comments');
  $seminars = "";

  foreach($this->input->post('seminar') as $value){
    $seminars .= "$value\n";
  } 

  $message = "$fname ($email) would like to register for the following seminars:\n$seminars and had this to say:\n\n$comments";

  $this->email->from($email, $fname);
  $this->email->to('john.doe@welovejesus.com');
  $this->email->subject('Seminar Registration');
  $this->email->message($message);
  $this->email->send();
  $this->load->view('formsuccess');
}
 

Now try and submit your form again. The e-mail should be sent and be waiting for you in your inbox.

Summary

In Part 1 we covered some of the basics of using CI and created our registration form. In Part 2 we went a little further by using CI's E-mail class to send the submitted form data to an e-mail address of our choice and also did some simple validations to ensure that certain fields were filled out properly. In our third and final part we will take a look at enabling CI to connect to a database and insert/view our submitted data to/from the database.

Download Code: regform-part2.zip

Discuss This Topic

  1. 1 Tobi

    Nice tutorial, Yannick! I also enjoyed part 1 of your introduction to Code Igniter and already downloaded the framework. ;-) As soon as I find some spare time, I will start hacking…

    God bless you!
    Tobi

     
  2. 2 Yannick

    Wonderful Tobi. Feel free to let me know how things are going when you start playing around with it and also don’t forget that if you have any questions you can ask me and I will see if I can be of assistance or even better the CI Forums are always buzzing with people to help. The User Guide is also very good.

    God bless you also.

     
  3. 3 Robert

    Great write up Yannick!

     
  4. 4 Nathan Smith

    Yannick: Thanks for parts 1 and 2. I’ve downloaded Code Igniter and have started reading the documentation, which is very well done. I look forward to reading any future CI tutorials you might be cooking up.

     
  5. 5 Yannick

    Thanks Nathan, glad the article was helpful and peeked your interest in CI. Let me know how you are finding it.

     
  6. 6 Olumide Otuyelu

    I had gone through the manuals that came with CI and found them easy to read and follow, still I find your approach in this tutorial very practicable, and just as easy to follow.

    Great work on your part, great exposure for a great framework ( I had frustratingly tried several, and found huge learning curves unsurmountable, until I came across CI )

    Once more PHP developers discover the use of ease and power of CI, this will be the deFacto platform bar-none.

    Just one happy programmer’s view (“happy” and “programmer” in the same sentence, who will have thunk)

     
  7. 7 William Wang

    Nice tutorial.Thanks a lot.
    Code igniter’s clean documentation is the reason I choose to learn it.
    And your tutorial is also a well-written one, it helps.

     
  8. 8 Yannick

    Olumide and William: Thanks for the kind words. I am happy that you liked the tutorial and that it was helpful. I couldn’t agree with your more that the CI documentation is excellent and props are most certainly in order for Rick Ellis for making such a wonderful framework.

     
  9. 9 richelle

    Just like the rest, my initial exposure to CI is becoming clear through the aid of this tutorial.

    As for the moment, I develop my php projects imploring some PEAR packages. To note, I find some similarities on CI’s helper Form with PEAR’s HTML_QuickForm. I am just wondering if it is still possible to invoke PEAR Packages when i use CI. I find PEAR’s Spreadsheet_Writer very indispensable on my work today because most of my clients require some reports to be viewable over the web and download it as an Excel file. Or, is there any CI library or helper available that does the requirement better.

    Great job… I hope to see more of this…

     
  10. 10 Yannick

    Hello Richelle,

    Having never used PEAR before I’m not sure how it plays with CI. I’d recommend making a post over at the CI Forums . More than likely someone there has tried and can tell you if it’s possible or not.

    I checked on the wiki and found an Excel plugin that will generate a tab-delimited file, and feed it to the client as an Excel file. Perhaps that could do what you’d like.

    Hope that helps. Blessings

     
  11. 11 Jefferson Campos

    Hello All,

    Great tutorial, thanks!

     
  12. 12 Ryan

    Hi Richelle,

    CI makes it very easy to create your own ancillary classes that can be autoladed and used like other classes in the framework.

    Here is a link to that part of the user guide

    Feel free to post on the boards if you have any problems. It’s very helpful over there.

     

Comments closed after 2 weeks.