2016-07-20 6 views
0

Я новичок в Cake PHP, и мне нужно проверить форму. Я запускаю приложение и отправляю его нормально, даже если поля пустые.Проблемы проверки формы Cake PHP

Я хочу, чтобы проверить их с правилами по умолчанию, используемые в UsersTables.php

Я был бы признателен, если кто-то помогает мне.

register.ctp:

<br> 
<div class="index large-4 medium-4 large-offset-4 medium-offset-4 columns"> 
    <div class="panel"> 
     <h2 class="text-center">Sign Up</h2> 
     <?= $this->Form->create(); ?> 

      <?php 
      echo $this->Form->input('name'); 
      echo $this->Form->input('email'); 
      echo $this->Form->input('password'); 
     ?> 
      <?= $this->Form->submit('Sign Up', array('class' => 'button')); ?> 


     <?= $this->Form->end(); ?> 
    </div> 
</div> 

Я хочу использовать этот код проверки ниже расположенные в UsersTable.php:

public function validationDefault(Validator $validator) 
    { 
     $validator 
      ->integer('id') 
      ->allowEmpty('id', 'create'); 

     $validator 
      ->requirePresence('nome', 'create') 
      ->notEmpty('nome'); 

     $validator 
      ->email('email') 
      ->requirePresence('email', 'create') 
      ->notEmpty('email'); 

     $validator 
      ->requirePresence('password', 'create') 
      ->notEmpty('password'); 



     return $validator; 
    } 

I импортированного торт \ Validation \ Validator; Я хочу понять, почему код проверки выше работает с формой «добавить» и другими.

UsersController.php:

<?php 
namespace App\Controller; 

use App\Controller\AppController; 
use Cake\Event\Event; 
use Cake\Validation\Validator; 


/** 
* Users Controller 
* 
* @property \App\Model\Table\UsersTable $Users 
*/ 
class UsersController extends AppController 
{ 



    /** 
    * Index method 
    * 
    * @return \Cake\Network\Response|null 
    */ 
    public function index() 
    { 
     $users = $this->paginate($this->Users); 

     $this->set(compact('users')); 
     $this->set('_serialize', ['users']); 
    } 

    /** 
    * View method 
    * 
    * @param string|null $id User id. 
    * @return \Cake\Network\Response|null 
    * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. 
    */ 
    public function view($id = null) 
    { 
     $user = $this->Users->get($id, [ 
      'contain' => [] 
     ]); 

     $this->set('user', $user); 
     $this->set('_serialize', ['user']); 
    } 

    /** 
    * Add method 
    * 
    * @return \Cake\Network\Response|void Redirects on successful add, renders view otherwise. 
    */ 
    public function add() 
    { 
     $user = $this->Users->newEntity(); 
     if ($this->request->is('post')) { 
      $user = $this->Users->patchEntity($user, $this->request->data); 
      if ($this->Users->save($user)) { 
       $this->Flash->success(__('The user has been saved.')); 

       return $this->redirect(['action' => 'index']); 
      } else { 
       $this->Flash->error(__('The user could not be saved. Please, try again.')); 
      } 
     } 
     $this->set(compact('user')); 
     $this->set('_serialize', ['user']); 
    } 

    /** 
    * Edit method 
    * 
    * @param string|null $id User id. 
    * @return \Cake\Network\Response|void Redirects on successful edit, renders view otherwise. 
    * @throws \Cake\Network\Exception\NotFoundException When record not found. 
    */ 
    public function edit($id = null) 
    { 
     $user = $this->Users->get($id, [ 
      'contain' => [] 
     ]); 
     if ($this->request->is(['patch', 'post', 'put'])) { 
      $user = $this->Users->patchEntity($user, $this->request->data); 
      if ($this->Users->save($user)) { 
       $this->Flash->success(__('The user has been saved.')); 

       return $this->redirect(['action' => 'index']); 
      } else { 
       $this->Flash->error(__('The user could not be saved. Please, try again.')); 
      } 
     } 
     $this->set(compact('user')); 
     $this->set('_serialize', ['user']); 
    } 

    /** 
    * Delete method 
    * 
    * @param string|null $id User id. 
    * @return \Cake\Network\Response|null Redirects to index. 
    * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found. 
    */ 
    public function delete($id = null) 
    { 
     $this->request->allowMethod(['post', 'delete']); 
     $user = $this->Users->get($id); 
     if ($this->Users->delete($user)) { 
      $this->Flash->success(__('The user has been deleted.')); 
     } else { 
      $this->Flash->error(__('The user could not be deleted. Please, try again.')); 
     } 

     return $this->redirect(['action' => 'index']); 
    } 

    public function register() 
    { 
     $user = $this->Users->newEntity(); 

     if($this->request->is('post')) 
     { 
      $user = $this->Users->patchEntity($user, $this->request->data); 

      if($this->Users->save($user)) 
      { 
       $this->Flash->success('Cadastro efetuado com sucesso'); 
       return $this->redirect(['action' => 'login']); 
      } 
      else 
      { 
       $this->Flash->error('Erro no cadastro'); 

      } 

      $this->set('user',$user); 
      $this->set('_serialize', ['user']); 

     } 
    } 

    public function login() 
    { 
     if($this->request->is('post')) 
     { 
      $user = $this->Auth->identify(); 

      if($user) 
      { 

       $this->Auth->setUser($user); 
       return $this->redirect(['controller' => 'comentario', 'action' => 'add']); 
      } 

      // Erro no Login 

      $this->Flash->error('Erro de autenticação'); 
     } 
    } 




    public function alterar() 
    { 
     $id = $this->Auth->user('id'); 
     $user = $this->Users->get($id); 

     if($this->request->is(['patch', 'post', 'put'])) 
     { 
      $user = $this->Users->patchEntity($user, $this->request->data); 

      if($this->Users->save($user)) 
      { 
       $this->Flash->success('Seus dados foram alterados'); 
      } 
      else 
      { 
       $this->Flash->error('Erro na alteração dos dados'); 
      } 
     } 
      $this->set(compact('user')); 
      $this->set('_serialize', ['user']); 

    } 


    public function logout() 
    { 
     $this->Flash->success('Sessão encerrada'); 
     return $this->redirect($this->Auth->logout()); 
    } 

    public function beforeFilter(Event $event) 
    { 
     $this->Auth->allow(['register']); 



    } 





} 
+0

сообщение контроллер, что» обрабатывая форму отправки, более чем вероятно «RegistersController» –

ответ

0
<br> 
<div class="index large-4 medium-4 large-offset-4 medium-offset-4 columns"> 
    <div class="panel"> 
     <h2 class="text-center">Sign Up</h2> 
     <?= $this->Form->create(); ?> 

      <?php 
      echo $this->Form->input('name'); 
      echo $this->Form->input('email'); 
      echo $this->Form->input('password'); 
     ?> 
      <?= $this->Form->submit('Sign Up', array('class' => 'button')); ?> 


     <?= $this->Form->end(); ?> 
    </div> 
</div> 

Заменить этот код с

<br> 
<div class="index large-4 medium-4 large-offset-4 medium-offset-4 columns"> 
    <div class="panel"> 
     <h2 class="text-center">Sign Up</h2> 
     <?= $this->Form->create($user); ?> 

      <?php 
      echo $this->Form->input('name'); 
      echo $this->Form->input('email'); 
      echo $this->Form->input('password'); 
     ?> 
      <?= $this->Form->submit('Sign Up', array('class' => 'button')); ?> 


     <?= $this->Form->end(); ?> 
    </div> 
</div> 

Добавить это в методе регистра вашего контроллера

public function register() 
    { 
     $user = $this->Users->newEntity(); 

     if($this->request->is('post')) 
     { 
      $user = $this->Users->patchEntity($user, $this->request->data); 

      if($this->Users->save($user)) 
      { 
       $this->Flash->success('Cadastro efetuado com sucesso'); 
       return $this->redirect(['action' => 'login']); 
      } 
      else 
      { 
       $this->Flash->error('Erro no cadastro'); 

      } 

     } 
     $this->set('user',$user); 
    } 
+0

Спасибо! проверка правильности работы, но я получил эту ошибку в форме: Notice (8): Неопределенная переменная: пользователь [APP/Template \ Users \ register.ctp, строка 8]. Что может быть? – Denis

+0

вы можете добавить в свой контроллер открытый регистр функций() { $ user = $ this-> Users-> newEntity(); if ($ this-> request-> is ('post')) { // зарегистрировать код } $ this-> set ('user', $ user); } –

+0

Я уже добавил. Я изменил $ this-> set (compact ('user')); to $ this-> set ('user', $ user); и я получаю неопределенную переменную ошибку. – Denis

Смежные вопросы