Vishal Kiri
Vishal Kiri

Reputation: 1306

How to make validation in cake php form

This is my cake php add.ctp file

<h2>Add New User</h2>

<!-- link to add new users page -->
<div class='upper-right-opt'>
  <?php echo $this->Html->link( 'List Users', array( 'action' => 'index' ) ); ?>
</div>

<?php 
 //this is our add form, name the fields same as database column names
  echo $this->Form->create('User');

  echo $this->Form->input('firstname');
  echo $this->Form->input('lastname');
  echo $this->Form->input('mobile');
  echo $this->Form->input('email');
  echo $this->Form->input('username');
  echo $this->Form->input('password', array('type'=>'password'));

 echo $this->Form->end('Submit');
?>


 <?php

This is my User controller code.

 class UsersController extends AppController {

public $name = 'Users';

public function index() {
    //to retrieve all users, need just one line
    $this->set('users', $this->User->find('all'));
}

public function add(){

    //check if it is a post request
    //this way, we won't have to do if(!empty($this->request->data))
    if ($this->request->is('post')){
        //save new user
        if ($this->User->save($this->request->data)){

            //set flash to user screen
            $this->Session->setFlash('User was added.');
            //redirect to user list
            $this->redirect(array('action' => 'index'));

        }else{
            //if save failed
            $this->Session->setFlash('Unable to add user. Please, try again.');

        }
    }
}

public function edit() {
    //get the id of the user to be edited
    $id = $this->request->params['pass'][0];

    //set the user id
    $this->User->id = $id;

    //check if a user with this id really exists
    if( $this->User->exists() ){

        if( $this->request->is( 'post' ) || $this->request->is( 'put' ) ){
            //save user
            if( $this->User->save( $this->request->data ) ){

                //set to user's screen
                $this->Session->setFlash('User was edited.');

                //redirect to user's list
                $this->redirect(array('action' => 'index'));

            }else{
                $this->Session->setFlash('Unable to edit user. Please, try again.');
            }

        }else{

            //we will read the user data
            //so it will fill up our html form automatically
            $this->request->data = $this->User->read();
         }

    }else{
        //if not found, we will tell the user that user does not exist
        $this->Session->setFlash('The user you are trying to edit does not exist.');
        $this->redirect(array('action' => 'index'));

        //or, since it we are using php5, we can throw an exception
        //it looks like this
        //throw new NotFoundException('The user you are trying to edit does not exist.');
    }


}

public function delete() {
    $id = $this->request->params['pass'][0];

    //the request must be a post request 
    //that's why we use postLink method on our view for deleting user
    if( $this->request->is('get') ){

        $this->Session->setFlash('Delete method is not allowed.');
        $this->redirect(array('action' => 'index'));

        //since we are using php5, we can also throw an exception like:
        //throw new MethodNotAllowedException();
    }else{

        if( !$id ) {
            $this->Session->setFlash('Invalid id for user');
            $this->redirect(array('action'=>'index'));

        }else{
            //delete user
            if( $this->User->delete( $id ) ){
                //set to screen
                $this->Session->setFlash('User was deleted.');
                //redirect to users's list
                $this->redirect(array('action'=>'index'));

            }else{  
                //if unable to delete
                $this->Session->setFlash('Unable to delete user.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
   }
  }
  ?>

Any one help me for make validation in my add.ctp file by using controller.

Upvotes: 1

Views: 756

Answers (1)

SkarXa
SkarXa

Reputation: 1194

I like doing validation with Modelless forms because it lets you separate validation from the entities and the save logic. You can implement it like this:

Create your form

// in src/Form/UserForm.php
namespace App\Form;

use Cake\Form\Form;
use Cake\Form\Schema;
use Cake\Validation\Validator;

class UserForm extends Form
{

    protected function _buildSchema(Schema $schema)
    {
        return $schema->addField('firstname', 'string')
            ->addField('lastname', ['type' => 'string'])
            ->addField('mobile', ['type' => 'string'])
            ->addField('email', ['type' => 'string'])
            ->addField('username', ['type' => 'string'])
            ->addField('password', ['type' => 'string']);
    }

    protected function _buildValidator(Validator $validator)
    {
        return $validator->add('firstname', 'length', [
                'rule' => ['minLength', 3],
                'message' => 'A name is required'
            ])->add('email', 'format', [
                'rule' => 'email',
                'message' => 'A valid email address is required',
            ]);
    }

    protected function _execute(array $data)
    {
        // Send an email.
        return true;
    }
}

You can add whatever rules you like in _buildValidator

Use it in the controller:

use App\Form\UserForm;

...

$form = new UserForm();
if ($this->request->is('post')) {
    if ($form->execute($this->request->data)) {
        //val ok
    } else {
        $this->Flash->error('Plese correct the form errors.');
    }
}
$this->set('form', $form);

Change your view to use the form.

echo $this->Form->create($form);

Upvotes: 1

Related Questions