【问题标题】:Problems to validate a form Cake PHP验证表单 Cake PHP 的问题
【发布时间】:2016-07-20 02:05:49
【问题描述】:

我是 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;
    }

我已经导入了 Cake\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']);



    }





}

【问题讨论】:

  • 发布处理表单提交的控制器,很可能是RegistersController

标签: forms validation cakephp


【解决方案1】:
<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);
    }

【讨论】:

  • 谢谢!验证它正在工作,但我在表单上收到此错误:注意 (8):未定义变量:用户 [APP/Template\Users\register.ctp,第 8 行]。可能是什么?
  • 你可以在你的控制器中添加公共函数 register(){ $user = $this->Users->newEntity(); if($this->request->is('post')){ // 注册码 } $this->set('user',$user); }
  • 我已经添加了。我修改了 $this->set(compact('user'));到 $this->set('user', $user);我得到未定义的变量错误。
  • 我的帖子更新了,请检查我帖子中的注册功能
  • 谢谢,现在一切正常!因此,错误被放在 if 语句中 $this->set('user', $user) 。再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-18
  • 1970-01-01
相关资源
最近更新 更多