Validate Form Using Model Without Table In Cakephp (eg- Contact Us form )
Form Validation is an essential task in any online application, its also an incredibly dull, tedious and repetitive task but with CakePHP you can cut down the time and effort you spend validating your form data. In a standard PHP application you will normally display the form for user input, try to validate the data, if errors exist redisplay the form showing the errors whilst keeping the data that was already submitted and go through the process again until the data successfully validates.
Create a Model “User” and copy paste this code
- <?php
- App::uses(‘Model’, ‘Model’);
- class User extends AppModel {
- var $useTable = false;
- var $_schema = array(
- ‘name’ =>array(‘type’=>‘string’, ‘length’=>100),
- ‘address’ =>array(‘type’=>‘string’, ‘length’=>255),
- ‘phone’ =>array(‘type’=>‘string’, ‘length’=>20),
- ‘subject’ =>array(‘type’=>‘string’, ‘length’=>255),
- ‘message’ =>array(‘type’=>‘text’)
- );
- var $validate = array(
- ‘name’ => array(
- ‘rule’ => ‘notEmpty’,
- ‘message’ => ‘required field’
- ),
- ‘address’ => array(
- ‘rule’ => ‘notEmpty’,
- ‘message’ => ‘required field’
- ),
- ‘phone’ => array(
- ‘rule’ => array(‘phone’, null, ‘us’),
- ‘message’ => ‘Please enter a valid phone eg. 5556668888’,
- ),
- ‘subject’ => array(
- ‘rule’ => ‘notEmpty’,
- ‘message’ => ‘required field’
- ),
- ‘message’ => array(
- ‘rule’ => ‘notEmpty’,
- ‘message’ => ‘required field’
- ),
- );
- }
For View
- <?php
- echo $this->Form->create(‘User’,array(‘novalidate’ => true));
- echo $this->Form->input(‘name’);
- echo $this->Form->input(‘address’);
- echo $this->Form->input(‘phone’);
- echo $this->Form->input(‘subject’);
- echo $this->Form->input(‘message’);
- echo $this->Form->end(‘Add’);?>
Action for Controller
- public function index()
- {
- if(!emptyempty($this->data))
- {
- //pr($this->data);die;
- if(isset($this->request->data[‘User’]))
- {
- $this->User->set($this->request->data[‘User’]);
- }
- if($this->User->validates())
- {}
- else {}
- }
- }
Now Run your code 🙂
I see a lot of interesting articles on your page. You have to spend a lot of time writing, i know
how to save you a lot of time, there is a tool that creates readable, google friendly posts in couple
of seconds, just type in google – k2 unlimited content
I read a lot of interesting posts here. Probably you spend a lot
of time writing, i know how to save you a lot
of work, there is an online tool that creates high quality, google
friendly posts in minutes, just search in google – laranitas free content source