Creating an Advanced Contact Form With Kohana – Part 1

Building An Advanced Contact Form With Kohana!

If you’ve never heard of the Kohana PHP Framework, then today is your lucky day. Kohana is a PHP 5 framework originally based off CodeIgniter, but with many improvements. We’ll start off slow as an introduction to getting started with Kohana, and then we will really dive into to our contact form, adding all sorts of features. Enough explaining, let’s do this!


Introducing Kohana!

Introducing Kohana!

live demo
Download

Tutorial Overview and Requirements

Before we get started, there are a few topics I recommend you have a basic understanding of, as well as a few basic server requirements you will need to meet.

What you will need to understand:

What you will need:

  • Before anything, please read the kohana overview! It is short and will get you started on a lot of the basics you need to know. Don’t forget about the Kohana Docs
  • Be sure to meet the server requirements. If you’re not sure, you can still participate, when we install, we will run a compatibility check that comes with Kohana.
  • Please ensure you have gone through some of the basic documentation above and any other basic documentation at http://docs.kohanaphp.com

Remember! If you’ve used CodeIgniter, Kohana will look very familiar to you, don’t be intimidated!

Step One – Install

The first thing we need to do is navigate to the Kohana home page and click on the download link at the top.

You will see a list of packages you can choose to include, such as an awesome payment library or perhaps you wanted to use the Google maps library. They are all great.

For now, the only package we need is the swift mailer package, make sure to include that in your Kohana download by checking the check mark. See the screenshot below:

download_page_swift

Once you have selected swift, click download and save the zip file to your computer as seen below:

Kohana Zip Download

Kohana Zip Download

Create a new directory on your server wherever you like, for example, in a folder named kohanaEmail. Whatever name you like is fine, just keep it short and simple. Drag the contents of your Kohana download into your newly created directory and upload everything. This may take a minute or two so be patient.

Configuration

Now that you have your files uploaded, we need to edit a configuration item or two. Kohana takes full advantage of separate config files and they can be extremely useful to you and your application.

Open up application/config/config.php and change the site domain item to your install location. For example, if you installed Kohana in a folder named ‘kohanaEmail’, then the config item would be /kohanaEmail/. See the screenshot below for an example:

Kohana Config Screenshot

Kohana Config Screenshot

Testing Your Server

Once all of the files have been uploaded, you need to navigate to the folder where you installed Kohana. For instance, if you installed Kohana in a folder named kohanaEmail, then navigate to http://yoursite.com/kohanaEmail/

Once you have done this, you should see a server configuration page, telling you wether you have passed or failed for a number of checks, and if you have passed or failed overall. Hopefully, you see something like the image below:

Kohana Install Pass

Kohana Install Pass

If you happened to fail on any item, no worries, check out the links on the docs or forums and do some trouble shooting.

At this point we will assumed your server has passed the check. You can now delete install.php and the .html documentation that came along with your install.

Now, ensure that applications/logs and applications/cache have a permission setting of 666.

Step Two – Routing

Before we dive into our Models, Views, & Controllers, we need to setup our routing preferences.

In Kohana, just like in other PHP frameworks, the URL is routed to different controller classes and methods.

Let’s say we wanted a URL like http://mysite.com/blog/article/my-php-article/. Our class would be named blog, one of our methods would be named article, and on of the arguments accepted by the article method would be an article name, in this case, my-php-article.

All we need to do is setup what controller should be called when our home page is loaded. We want our contact page and form to show when our page is loaded.

  • Open /system/config/routes.php and make a copy of this file.
  • Move this copy to applications/config/routes.php
  • Change the route name to ‘contact’, this is a controller we will be creating shortly

Your config folder and file structure should now look like the images below:

Config File Structure

Config File Structure

routes.php File

routes.php File

Kohana File Structure

Take a minute to get familiar with the Kohana file structure. All of our files will be going into the applications folder. Kohana uses a cascading file system, a little bit like WordPress does it, which is very powerful. See the screenshot below for an idea of Kohana file layout:

Kohana File System

Kohana File System

Step Three – Views

We will go ahead and setup our basic views and template structure. Even though this is just a beginners ‘part one’ tutorial, we want to keep our views and template flexible. You will need to create four new files in your views/ folder.

  • base_template.php – is our main template structure that will layout everything.
  • header.php – contains our header and title information.
  • contact_form.php – holds our form data.
  • footer.php – holds our footer information and closing body and html tags.

Your views/ folder should look similar to below:

View File Structure

View File Structure

base_template.php

Base template is a very flexible view file, it holds the structure and general layout for all of the rest of our views. Open up base_template.php and add the following.

<?php if (!defined('SYSPATH')) exit('No direct script access allowed'); ?>
<?php echo $header; ?>
	<div id='wrap'>
		<?php echo $content; ?>
	</div>	

<?php echo $footer; ?>

header.php

header.php will hold all of our <heade> data, title tag, and opening body/html tags. Open header.php and add the following:

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title><?php echo $title; ?></title>
</head>

<body>

footer.php

footer.php is very simple and just contains some closing tags, although it could contain any copyright information, links etc. Open up footer.php and insert the following:

</body>
</html>

contact_form.php

For our contact form, we are going to use the form helper that Kohana provides. Take a minute to read through the form helper so you understand what is going on.

Form Documentation

Form Documentation

Open up contact_form.php and insert the following. We will be adding a few more things to this later.

<?php echo form::open('contact'); ?>

<?php echo form::label('contact_name', 'Your Name'); ?>
<?php echo form::input('contact_name'); ?>

<?php echo form::label('contact_email', 'Your Email');?>
<?php echo form::input('contact_email'); ?>

<?php echo form::label('contact_subject', 'Email Subject'); ?>
<?php echo form::input('contact_subject'); ?>

<?php echo form::label('contact_message', 'Your Message'); ?>
<?php echo form::textarea('contact_message'); ?>

<?php echo form::submit('contact_submit', 'Send it!'); ?>

<?php echo form::close(); ?>

It’s now time to setup our controller to render our views…

Controller Basics

Create a new controller in your controller file named contact.php. Open it up and paste in the following:

<?php if (!defined('SYSPATH')) exit('No direct script access allowed');
/**
  * Contact_Controller - Used for validating and sending emails from form.
  *
  */
  class Contact_Controller extends Controller
  {

  	public function __construct()
  	{
  		parent::__construct();
  	}

  	public function index()
  	{

  		//Setup base view
  		$view = new View('base_template');

  		//Setup header
  		$view->header = new View('header');

  		//Setup header title
  		$view->header->title = 'Kohana Contact Form by Drew Douglass';

  		//Setup content view
  		$view->content = new View('contact_form');

  		//Setup footer view
  		$view->footer = new View('footer');

  		//Render view
  		$view->render(TRUE);

  	}

  }

This is the absolute essentials you need to render your form. If you navigate to your Kohana install, you should now see your form, complete with all of your rendered html. With some very basic styles, you should see something like below:

Basic Form View

Basic Form View

Now, we need to start doing the fun work, modifying our controller to handle, validate, and send the contact form request, or load the necessary views and errors.

Please note, since this is a part one tutorial, we will focus on the controller basics. There will be room for us in part two to improve the flexibility and re usability of this code.

The Controller

I’ve kept the controller pretty well commented, so have a look through each line, one line at a time, and then will hit on some important bullet points and references. Open up contact.php in your controllers folder and change it to the following:

<?php if (!defined('SYSPATH')) exit('No direct script access allowed');
/**
  * Contact_Controller - Used for validating and sending emails from form.
  *
  */
  class Contact_Controller extends Controller
  {

  	public function __construct()
  	{
  		parent::__construct();
  	}

  	public function index()
  	{
  		//Setup view without rendering
  		//Setup base view
  		$view = new View('base_template');

  		//Setup header
  		$view->header = new View('header');

  		//Setup header title
  		$view->header->title = 'Kohana Contact Form by Drew Douglass';

  		//Setup content view
  		$view->content = new View('contact_form');

  		//Setup footer view
  		$view->footer = new View('footer');

  		//Setup default form values so we can repopulate the form
  		$form = array
  		(
  			'contact_name' => '',
  			'contact_email' => '',
  			'contact_subject' => '',
  			'contact_message' => ''
  		);

  		//copy the form fields into the errors for later...
  		$errors = $form; 

  		//Check to see if the form was submitted
  		if(isset($_POST['contact_submit']))
  		{
  			//Add the rules we need to validate our form
  			$post = new Validation($_POST);

  			//filter the whitespace from beginning and ends of fields
  			$post->pre_filter('trim');

  			//Add rules for contact_name
  			$post->add_rules('contact_name', 'required', 'standard_text', 'length[2,20]');

  			//Add rules for contact_email
  			$post->add_rules('contact_email', 'required', 'email', 'email_domain');

  			//add rules for subject
  			$post->add_rules('contact_subject', 'required', 'length[5,30]', 'standard_text');

  			//Add rules for message
  			$post->add_rules('contact_message', 'required', 'standard_text');

  			//If there were no errors...
  			if($post->validate())
  			{
  				//Load the config file with our email address defaults
  				//This make our app more portable
  				$email_config = Kohana::config_load('email');

  				//Send it and render the view with message.
  				$to = $email_config['default_email'];
  				$from = $this->input->post('contact_email');
  				$subject = $this->input->post('contact_subject');
  				$message = $this->input->post('contact_message');

  				//Add some info to the end of the message for reference
  				$message .= "\n\n This message was sent to you from".$this->input->post('contact_name')." and the email given is ".$from;

  				if(email::send($to, $from, $subject, $message, TRUE))
  				{
  					$view->content->set('form_values', $form);
  					$view->content->set('message', 'Your email was sent!');
  					$view->render(TRUE);
  				}
  				else
  				{
  					die('We had a technical error, please try again.');
  				}
  			}

  			//else we got errors...
  			else
  			{
  				//repopulate form values
  				$form = arr::overwrite($errors, $post->as_array());

  				//setup the errors
  				$errors = arr::overwrite($errors, $post->errors('form_errors'));

  				//pass the form values and errors to the view
  				$view->content->set('errors', $errors);
  				$view->content->set('form_values', $form);

  				//Render the view with errors and values
  				$view->render(TRUE);
  			}

  		}
  		//form was not submitted, just show it.
  		else
  		{
  			$view->content->set('form_values', $form);
			$view->render(TRUE);
  		}

  	}

  }
  • On line 16-42, we just go through some basic view and default value setups.
  • Line 45 checks to see if the form was submitted, and if so sets up all the validation rules. Please see the validation library for more details.
  • Line 66 checks to see if the form fields validated, and if they did, it loads some info from a config file we will make shortly, and send the email with a custom success message.
  • Lines 97-107 attach the errors and form values (so the user doesn’t lost what they have entered so far) to the view and render the errors and form.

Now that we have the whole controller, you may have noticed there is some changes we need to make to the view, as well as a new filed or two we will need to create. Bare with me, we’re through the hardest part!

Note that the index() method above is quite large, in later series, we will review how to shorten this and make use of private methods.

Step Four – Your New View

Now that we have passed and attached default values and errors in the controller above, we need to display them in our view if they exist. Open up contact_form.php in your views folder and change it to the following:

<?php echo form::open('contact'); ?>

<?php if(isset($errors)) : foreach($errors as $error) : ?>
	<div><strong><em><?php echo $error; ?></em></strong></div>
<?php endforeach;endif; ?>

<?php if(isset($message)): ?>
	<h2><?php echo $message;?></h2>
<?php endif; ?>

<?php echo form::label('contact_name', 'Your Name'); ?>
<?php echo form::input('contact_name', $form_values['contact_name']); ?>

<?php echo form::label('contact_email', 'Your Email');?>
<?php echo form::input('contact_email', $form_values['contact_email']); ?>

<?php echo form::label('contact_subject', 'Email Subject'); ?>
<?php echo form::input('contact_subject', $form_values['contact_subject']); ?>

<?php echo form::label('contact_message', 'Your Message'); ?>
<?php echo form::textarea('contact_message', $form_values['contact_message']); ?>

<?php echo form::submit('contact_submit', 'Send it!'); ?>

<?php echo form::close(); ?>

Step Five – Custom Error Messages

Remember how we used $post->add_rules() to set validation rules in our controller? Now we need to setup custom error messages for our form. Kohana makes this very flexible and re usable by having us create a new file.

Create a new file named form_errors.php. Paste in the following:

<?php
$lang = array
(
		'contact_name' => array
			(
				'required' => 'The name field cannot be left blank.',
				'standard_text' => 'Only standard text allowed in the name field.',
				'length' => 'The name field must be between 2 and 20 characters in length.',
			),

		'contact_email' => array
			(
				'required' => 'The email field cannot be left blank.',
				'email' => 'The email must be in a valid email format.',
				'email_domain' => 'The email must be a valid email address.',
			),

		'contact_subject' => array
			(
				'required' => 'The subject cannot be left blank.',
				'length' => 'The subject must be between 5 and 30 characters in length.',
				'standard_text' => 'The subject can only contain standard text characters.',
			),

		'contact_message' => array
			(
				'required' => 'The message field cannot be left blank.',
				'standard_text' => 'The message can only contain standard text characters.',
			)
);

Now, create a new folder in your applications folder named i18n. Inside this folder, create another folder named en_US. Place the form_errors.php file inside of applications/i18n/en_US/form_errors.php.

You can now use this file for more forms on your site, add new fields, or create a new file if you prefer.

In case you need any further clarification, your folder structure should look similar to this:

Structure

Structure

Step Six – Email Config

You’re almost done! Open up system/config/email.php and make a copy. Place the copy inside your applications/config folder.

Open up your email.php file in your config folder. Add the following at the bottom, and replace your email in the quotes:

$config['default_email'] = 'youremail@example.com';

Your email config file should now look something like this:

Email Config File

Email Config File

Done! Try out your form!

If you’ve followed all the steps, you should have a working Kohana contact form now. Try it out and see how the errors messages work and how the values remain intact.

Errors Found...

Errors Found...

Success!

Success!

Our form is still relatively basic, but now that we have the framework layed out, we can go back and start adding and editing in some awesome features!

What’s Next?

In our coming series, we are really go to take our contact form to the next level. We’ll learn how to break down our methods into smaller methods and increase re usability. We will also discuss:

  • Email Attachments
  • Captchas and other spam protection
  • HTML Template Emails
  • Javascript/AJAX enhancements.

Be sure to head over to Kohana and read up on the documentation and helpers, you might be surprised how much functionality Kohana comes with!

Related posts:

  1. PHP CodeIgniter Validation
  2. Creating a Sleek Calendar
  3. A Detailed Django Tutorial: Blog Basics Part IV
  4. Building a jQuery Step-by-Step Form


Tags: ,

Written by Drew Douglass

Hey, I'm Drew Douglass and I'm a freelance web developer based out of Missouri. I love building sites and teaching others tricks dealing with php and WordPress. I work at Envato Support and also run Dev-Tips.com & CreatingDrew. You can check out my portfolio and learn more about me if you like.

 

13 Responses to “Creating an Advanced Contact Form With Kohana – Part 1”

  1. Karl Roos Says:

    November 25th, 2009 at 10:21 am

    You just got yourself a spot in Google Reader. Great tut, keep it up.

  2. Abhin Says:

    November 25th, 2009 at 11:06 pm

    great tut, looking forward for the next tut :)

  3. Bicho44 Says:

    November 28th, 2009 at 5:33 pm

    Great! Thanks
    I will follow

  4. Tash Pemhiwa Says:

    December 3rd, 2009 at 7:57 pm

    Well done! Check out my quick and dirty setup tutorial over at my blog: http://breaktime.yolasite.com/
    Cheers!

  5. antpaw Says:

    December 5th, 2009 at 6:07 am

    good tut! i think its better to setup the validation function inside of the model class. so it can be reused.

  6. ulotnachwila87 Says:

    January 29th, 2010 at 8:21 pm

    great :)

    when will be next part?

  7. Abdullah Al Mamun Says:

    March 12th, 2010 at 3:08 pm

    Awesome tutorial to get started with Kohana.
    Tried and works fine. Can’t wait anymore for the next part, could you please continue…………

  8. 7 Secure, Lightweight, and Easy to Use PHP Frameworks | DevSnippets Says:

    March 29th, 2010 at 7:04 am

    [...] – Creating an Advanced Contact Form With Kohana [...]

  9. Kohana – Swift, Secure, Lightweight, and Easy to Use PHP Framework | GuiDesigner Says:

    April 1st, 2010 at 6:59 am

    [...] – Creating an Advanced Contact Form With Kohana [...]

  10. 7 Secure, Lightweight, and Easy to Use PHP Frameworks - www.huedesigner.com Says:

    May 19th, 2010 at 4:05 am

    [...] - Creating an Advanced Contact Form With Kohana [...]

  11. Patrick Says:

    December 3rd, 2010 at 2:34 pm

    I would add a reverse captcha to this as well

  12. monn Says:

    January 14th, 2011 at 2:04 am

    How about in kohana3? please provide same examples as this (composed of picture and step to step basis)

    Thanks

  13. Online Friendly » Around the Office: hands-on with Kohana, picture sharing with DailyBooth, and more Says:

    June 10th, 2011 at 2:33 pm

    [...] Roberto had a very good first impression of PHP5 framework Kohana, and actually liked its modules for database interactivity and cookies. With its basic template system, simple installation, and online learning resources, he’d recommend it to developers who want to save lines of code and time, but be warned, it only works with PHP 5. For those new to Kohana, he’d recommend starting with a tutorial on creating an advanced contact form. [...]

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 
connect with me!