CakePHP 1.2 : Creating a Contact Form
Join the DZone community and get the full member experience.
Join For FreeMost 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:
class Contact extends AppModel {
var $useTable = false;
var $_schema = array(
'name' =>array('type'=>'string', 'length'=>100),
'email' =>array('type'=>'string', 'length'=>255),
'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:
var $validate = array(
'name' => array(
'rule'=>array('minLength', 1),
'message'=>'Name is required' ),
'email' => array(
'rule'=>'email',
'message'=>'Must be a valid email address' ),
'details' => array(
'rule'=>array('minLength', 1),
'message'=>'Feedback is required' )
);
With the model now set up and ready to go, setting up the view is a piece of cake:
<?php
echo $form->create('Contact');
echo $form->inputs();
echo $form->end('Send');
?>
Then, all we have to do is set up our controller to do something.
function add() {
if ($this->RequestHandler->isPost()) {
$this->Contact->set($this->data);
if ($this->Contact->validates()) {
//send email using the Email component
$this->Email->to = 'admin@example.com';
$this->Email->subject = 'Contact message from ' . $this->data['Contact']['name'];
$this->Email->from = $this->data['Contact']['email'];
$this->Email->send($this->data['Contact']['details']);
}
}
}
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.
Published at DZone with permission of Jonathan Snook. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Operator Overloading in Java
-
Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
-
SRE vs. DevOps
-
Reactive Programming
Comments