2011-06-11 81 views
2

我有以下動作來顯示形式如何在Zend中提交表單?

public function showformAction() { 
    $this->view->form = new Form_MyForm(); 
    $this->view->form->setAction('submitform'); 
} 

上面的動作示出了形式成功地僅具有一個文本區域和提交按鈕。

,我使用下面的操作來提交上述表格:

public function submitformAction() { 

    $form = new Form_MyForm(); 
    $request = $this->getRequest(); 

     if ($request->isPost()) { 
      $values = $form->getValues(); 
      print_r($values);die();  
     } else { 
      echo 'Invalid Form'; 
     } 
} 

上述動作爲顯示輸出:

Array ([myfield] =>) 

這意味着它是不正確張貼值始終顯示爲空數組或我沒有正確獲取發佈的值。如何將值發佈到submitformAction()。

感謝

回答

5

我認爲你必須訪問提交的表單的值之前使用isValid(),因爲它就在那裏,該值被選中並且增值

public function submitformAction() { 

    $form = new Form_MyForm(); 
    $request = $this->getRequest(); 

     if ($request->isPost()) { 
      if ($form->isValid($request->getPost())) { 
       $values = $form->getValues(); 
       print_r($values);die();  
      } 
     } else { 
      echo 'Invalid Form'; 
     } 
} 
+0

是的你是對的。但是在你檢查isValid()的地方使用'$ request-> getPost()'而不是'$ _POST'。謝謝 – Student 2011-06-11 12:05:37

2

在補充@VAShhh響應。有了更多的細節: 您需要做兩件事,用張貼的數據填充表單域,並將安全性過濾器和驗證程序應用於該數據。 Zend_Form提供了一個簡單的函數,它執行兩個,它是isValid($data)

所以你應該:

  1. 建立表單
  2. 測試你是一個POST請求
  3. 填充&過濾&驗證此數據
  4. 無論是處理事實可能是無效的,並重新 - 顯示現在的形式 裝飾有錯誤從表格中檢索有效數據

所以,你應該得到:

function submitformAction() { 
    $form = new Form_MyForm(); 
    $request = $this->getRequest(); 

    if ($request->isPost()) { 
     if (!$form->isValid($request->getPost())) { 
      $this->view->form = $form; 
      // here maybe you could connect to the same view script as your first action 
      // another solution is to use only one action for showform & submitform actions 
      // and detect the fact it's not a post to do the showform part 
     } else { 
      // values are secure if filters are on each form element 
      // and they are valid if all validators are set 
      $securizedvalues = $form->getValues(); 
      // temporary debug 
      print_r($securizedvalues);die(); 
      // here the nice thing to do at the end, after the job is quite 
      // certainly a REDIRECT with a code 303 (Redirect after POSt)  
      $redirector = $this->_helper->getHelper('Redirector'); 
      $redirector->setCode(303) 
       ->setExit(true) 
       ->setGotoSimple('newaction','acontroller','amodule'); 
      $redirector->redirectAndExit(); 
    } else { 
      throw new Zend_Exception('Invalid Method'); 
    } 
} 

並在代碼作爲所述重新顯示窗體你shoudl真正嘗試使用相同的功能均顯示和操作崗位作爲很多步驟都是真的相同的:

  • 建築形式
  • 示出它在視圖中錯誤的情況下

通過檢測請求是一個POST,您可以檢測到您處於POST處理情況。

+0

感謝您的詳細信息.. – Student 2011-06-11 12:18:47