Creating a Contact Form in CakePHP

Most contact forms take a name and feedback from a user and mail it off to the administrator but don’t store any information in the database. This tutorial will show how to use CakePHP’s models, even when no table is being used.

CakePHP is great in that you set up a database table, define an empty class file for the Model and suddenly you’re halfway there. The Form helper can automatically display error messages and outputs the proper input type depending on the field data type.

However, what do you do when you don’t have a database table, as is the case with our contact form? We look to the model property, _schema. Normally this is automatically populated by CakePHP when it figures out what the database says. With no database table, you have to define the schema by hand.

Here’s an example schema for our contact form:

1.class Contact extends AppModel {
2.var $useTable = false;
3.var $_schema = array(
4.'name'       =>array('type'=>'string', 'length'=>100),
5.'email'      =>array('type'=>'string', 'length'=>255),
6.'details'    =>array('type'=>'text')

As you can see, we’ve told the model not to use a table by setting useTable to false. Then, we define the schema for the table. In this case, we’re going to ask the site visitor to fill out name, email, and contact details.

With the schema defined, we can also specify some validation rules to go along with that:

01.var $validate = array(
02.'name' => array(
03.'rule'=>array('minLength', 1),
04.'message'=>'Name is required' ),
05.'email' => array(
07.'message'=>'Must be a valid email address' ),
08.'details' => array(
09.'rule'=>array('minLength', 1),
10.'message'=>'Feedback is required' )

With the model now set up and ready to go, setting up the view is a piece of cake:

2.echo $form->create('Contact');
3.echo $form->inputs();
4.echo $form->end('Send');

Then, all we have to do is set up our controller to do something.

01.function add() {
02.if ($this->RequestHandler->isPost()) {
04.if ($this->Contact->validates()) {
05.//send email using the Email component
06.$this->Email->to = [email protected]'
07.$this->Email->subject = 'Contact message from ' . $this->data['Contact']['name']; 
08.$this->Email->from = $this->data['Contact']['email']; 

And that’s it! The process for the contact form, validating and sending emails hasn’t changed. All we had to do was define the schema to be able to take advantage of our model validation.

Leave a Reply