如何在蛋糕PHP形式进行验证

时间:2015-10-28 12:50:15

标签: php cakephp-3.0

这是我的蛋糕php add.ctp文件

<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

这是我的用户控制器代码。

 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'));
            }
        }
    }
   }
  }
  ?>

任何人都可以通过使用控制器来帮助我在add.ctp文件中进行验证。

1 个答案:

答案 0 :(得分:1)

我喜欢使用Modelless forms进行验证,因为它允许您将验证与实体和保存逻辑分开。您可以像这样实现它:

创建表单

// 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;
    }
}

您可以在_buildValidator

中添加您喜欢的任何规则

在控制器中使用它:

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);

更改您的观点以使用表单。

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