2012-01-26 19 views
4

看看這個代碼:CakePHP的2.0檢測請求類型是奇怪行爲

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); 
    } 

當我在此動作對應的視圖提交表單,看來這 - $>請求 - >是( 'post')返回false。運行if/else語句的另一端。這裏的怪異位 - POST數據是存在的,而且我調試調用($這個 - >請求 - >數據)吐出我期待中的數據!

下面是被傳遞的數據:

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

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

    ) 

) 

現在,我當然可以只改變$這個 - >請求 - >是(「後」)空($這個 - >請求 - >數據),但這並不能解決問題。

那麼什麼是錯我的代碼?這是怎麼回事?

謝謝!

+0

確實你的觀點是什麼樣子?特別是你提交的表單。 – Oldskool

+0

它產生上述的POST數據 - 當然這是對美景的相關信息(道歉,如果我想的東西)? – Will

回答

13

嘗試使用這樣的:

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

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

+0

謝謝。我想過這樣做,但我的表單行爲被設置爲「發佈」。蛋糕必須看到我正在更新一些東西。用於更新的HTTP標準請求類型是PUT。 –

1

當您在CakePHP中,表單助手形式::創建()將使用$這 - >請求 - >數據的信息,以檢測您的表單是否爲添加表單或更新表單。如果您的模型主鍵位於您的數據中,則會生成隱藏的輸入字段以覆蓋默認的HTTP方法。發生這種情況是因爲你可能會更新某些東西

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

要檢查您的表單提交,當您創建或更新的東西,你可以傳遞一個數組CakeRequest ::是()這樣說:

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

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

+0

嘿。請解釋*爲什麼*他可以試試這個,以及它如何解決問題。我們想要堆棧溢出的質量答案,這在這裏有些被忽略。 –

+1

嗨,我更新我的回答有更多的信息和來源。 –