【问题标题】:Is that possible to save data with form submission是否可以通过表单提交保存数​​据
【发布时间】:2020-05-04 00:15:23
【问题描述】:

控制器代码:

    public function login()
    {
        $this->LoadModel('Users');

        pr($this->data);
    }

查看代码:

<?php echo
$this->Form->create('Post').
$this->Form->control('email').'<br>'.
$this->form->label('password').'<br>'.
$this->Form->password('password').'<br>'.
$this->Form->submit('log in').
$this->Form->end();
?>

我不明白数据是提交给控制器,而是从控制器读取数据。 我用控制器保存了该数据,但要访问数据变量,即提交无法读取到控制器的表单数据。

【问题讨论】:

  • 您想在控制器中发布数据吗?是你的问题吗?
  • 是的,这就是我的问题。
  • 我想将数据发布到控制器。
  • 是的,我想在控制器中发布数据,这样我就可以使用插入命令将数据保存到数据库中。请尽快回复答案,因为我真的希望该代码能够正常工作。目的是用答案解决问题,让我在将表单提交到控制器后将数据保存到数据库。善待并尽快回复。谢谢。

标签: php form-submit cakephp-4.x


【解决方案1】:

要获取发布数据,请使用调试

debug($this->request->getData()); 

看起来您需要所有 CRUD 代码。

所以,你可以在下面创建你的用户 add.ctp 文件

位置:模板\用户\add.ctp

<?= $this->Form->create($user) ?>

<?php
   echo $this->Form->control('username');
   echo $this->Form->control('email');
   echo $this->Form->control('password');
?>

<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

然后用户控制器看起来像

 UsersController/add method look like 

 public function add()
    {
        $user = $this->Users->newEmptyEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

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

你需要更多吗? 只需要在你的应用文件夹中给出一个简单的命令来生成你的 CRUD。

下达命令

bin/cake bake all users

假设,users 是你的数据库表名。 然后你会得到添加,编辑,删除,查看。 can see this tutorial for see how to give cake bake command

【讨论】:

  • 感谢您的回答,它解决了大部分问题,但是将数据保存到数据库中,我也会得到响应。请谢谢。
  • 您将使用方法save()将数据保存在数据库中,您不需要编写插入查询。通过保存插入查询管理。
  • 好的,我明白了,所以我让代码流动,但我无法保存数据,因为转到:$this->Flash->error(__('无法保存用户。请,再试一次。'));
  • 这无法保存然后你得到错误。这里可能有很多问题。有关详细信息,请参阅 logs/error.log。
  • 没有错误,但只有闪存消息,但我会继续阅读代码并返回。谢谢。
猜你喜欢
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-01
  • 2011-03-20
  • 1970-01-01
相关资源
最近更新 更多