2015-10-28 2 views
1

Это мой торт PHP add.ctp файлКак сделать проверку в форме торта PHP

<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 файле с помощью контроллера.

+0

http://book.cakephp.org/3.0/en/core-libraries/validation.html –

+0

Я знаю @KaushikMaheta. Можете ли вы сделать реализацию для нас. Мы очень этому рады. Спасибо. –

ответ

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); 
Смежные вопросы