【问题标题】:CakePHP 2.0 detecting request type is behaving oddlyCakePHP 2.0 检测请求类型的行为很奇怪
【发布时间】:2012-02-19 13:47:33
【问题描述】:

看看这段代码:

   if ($this->request->is('post')){
        $this->request->data['Profile']['userId'] = $this->Auth->user('id');
        if ($this->Profile->save($this->request->data)){
            $this->Profile->setPermissions($this->Profile->id, $this->request->data['Permission']);
            $this->NFSSession->setSuccessMessage('Your profile has been updated.');
        }else{
            $this->NFSSession->setSuccessMessage('There was a problem updating your profile.  Please try again.');
        }
    }else{
        echo 'Not a post request!!?!?!?!?!';
        debug($this->request->data);
    }

当我在此操作的相应视图中提交表单时,似乎 $this->request->is('post') 返回 false。 if/else 语句的另一端运行。这是奇怪的一点 - POST 数据在那里,我对 debug($this->request->data) 的调用吐出了我期待的数据!

这是传递的数据:

Array
(
[Profile] => Array
    (
        [aboutMe] => Hey there
    )

[Permission] => Array
    (
        [Profile] => Array
            (
                [aboutMe] => 1
            )

    )

)

现在,我当然可以将 $this->request->is('post') 更改为 !empty($this->request->data) 但这不会直接解决问题。

那么我的代码有什么问题吗?怎么回事?

谢谢!

【问题讨论】:

  • 您的视图是什么样的?特别是您提交的表单。
  • 它生成上述 POST 数据 - 当然这是关于视图的唯一相关信息(如果我遗漏了什么,请道歉)?

标签: cakephp cakephp-2.0


【解决方案1】:

试试这个:

if ($this->request->is('post') || $this->request->is('put'))

http://cakephp.lighthouseapp.com/projects/42648/tickets/2353

【讨论】:

  • 谢谢。我想尝试一下,但我的表单操作设置为“发布”。蛋糕必须看到我正在更新一些东西。用于更新的 HTTP 标准请求类型是 PUT。
【解决方案2】:

当您在 CakePHP 中创建表单时,FormHelper::create() 将使用 $this->request->data 中的信息来检测您的表单是添加表单还是更新表单。如果您的模型主键在您的数据中,则会生成一个隐藏的输入字段来覆盖默认的 HTTP 方法。发生这种情况是因为您可能会更新一些内容。

<form id="RecipeEditForm" method="post" action="/recipes/edit/5">
    <input type="hidden" name="_method" value="PUT" />
    ...
</form>

要检查您的表单是否在您创建或更新某些内容时提交,您可以通过以下方式将数组传递给 CakeRequest::is():

if($this->request->is(array('post','put')) {
    //...
}

更多信息:http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-forms

【讨论】:

  • 你好。请解释为什么他也可以尝试这个,以及它将如何解决问题。我们希望在 Stack Overflow 上获得高质量的答案,而这在这里有些被忽视了。
  • 嗨,我用更多信息和来源更新了我的答案。
猜你喜欢
  • 2017-09-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多