2012-05-04 56 views
0

我已經使用zend表單創建了一個表單,該表單位於applications目錄中的表單目錄中。我已經在控制器中創建這種形式的實例:將Zend_Form在視圖中提交的數據傳遞給模型

public function getBookSlotForm(){ 
     return new Application_Form_BookSlot(); 
    } 
public function bookSlotAction() 
    { 
    $form = $this->getBookSlotForm(); 
    $this->view->form = $form; 
    } 

它顯示給用戶的視圖:

echo $this->form; 

當用戶在表單填寫,我該怎麼辦我店模型中的變量中的數據?

回答

1

蒂姆到目前爲止是正確的,但你似乎需要更多的細節。你似乎沒有讓你的表單顯示在頁面上的問題。現在,將表單中的數據存入您的控制器,然後再轉到您想要的任何模型上,這非常簡單直接。

我打算假設您在本示例的表單中使用了post方法。

當您在任何php應用程序中發佈您的表單時,它會將其數據以陣列形式發送到$_POST變量。在ZF這個變量被存儲在請求對象中的FrontController,並與$this->getRequest()->getPost()通常訪問並且將返回值的相關聯的陣列:使用延伸Zend_Form你應該訪問自己的形式形成時

//for example $this->getRequest->getPost(); 
POST array(2) { 
    ["query"] => string(4) "joel" 
    ["search"] => string(23) "Search Music Collection" 
} 

//for example $this->getRequest()->getParams(); 
PARAMS array(5) { 
    ["module"] => string(5) "music" 
    ["controller"] => string(5) "index" 
    ["action"] => string(7) "display" 
    ["query"] => string(4) "joel" 
    ["search"] => string(23) "Search Music Collection" 
} 

作爲特殊情況值將使用$form->getValues(),因爲這將返回已應用了表單篩選器的表單值,因此getPost()getParams()將不會應用表單篩選器。

所以,現在我們知道我們是從發送值模型的過程中接收相當簡單:

public function bookSlotAction() 
{ 
    $form = $this->getBookSlotForm(); 
    //make sure the form has posted 
    if ($this->getRequest()->isPost()){ 
     //make sure the $_POST data passes validation 
     if ($form->isValid($this->getRequest()->getPost()) { 
     //get filtered and validated form values 
     $data = $form->getValues(); 
     //instantiate your model 
     $model = yourModel(); 
     //use data to work with model as required 
     $model->sendData($data); 
     } 
     //if form is not vaild populate form for resubmission 
     $form->populate($this->getRequest()->getPost()); 
    } 
    //if form has been posted the form will be displayed 
    $this->view->form = $form; 
} 
0

典型的工作流程是:

public function bookSlotAction() 
{ 
    $form = $this->getBookSlotForm(); 
    if ($form->isValid($this->getRequest()->getPost()) { 
     // do stuff and then redirect 
    } 

    $this->view->form = $form; 
} 

調用的isValid()也將存儲在表單對象中的數據,因此,如果驗證失敗,您的形式將與用戶輸入的填充數據再次顯示

相關問題