2015-02-24 77 views
0

我試圖用crsf令牌來保護我的Zend表格。總而言之,如果我將標記元素添加到我的表單中,它總是會將標記的非空錯誤消息發回給我。我在做錯什麼? THXZend表格+ csrf保護

class Application_Form_Test3 extends Zend_Form { 

    public function init() { 
     $this->setMethod('post'); 

//..some elements 

     $note = new Zend_Form_Element_Textarea('note'); 
     $note->addValidator('stringLength', false, array(2, 50)); 
     $note->setRequired(true); 
     $note->class = 'form-control'; 
     $note->setLabel('Poznámka:'); 
     $note->setAttrib('placeholder', 'poznamka ke spisu'); 
     $note->setOptions(array('cols' => '20', 'rows' => '4')); 

     $submit = new Zend_Form_Element_Submit('submit'); 
     $submit->class = 'btn btn-success'; 
     $submit->setValue('odeslat'); 

     $this->addElements(array(
      $number, 
      $year, 
      $owner, 
      $note, 
      $submit, 
     )); 

     $this->addElement('hash', 'no_csrf_foo', array('salt' => 'unique')); 
    } 

} 

動作控制器:

public function findAction() { 
    $request = $this->getRequest(); 
    $form = new Application_Form_Test3(); 

    if ($this->getRequest()->isPost()) { 
     if ($form->isValid($request->getPost())) { 
      var_dump($request->getPost()); 
     } else { 
      var_dump("ERROR"); 
     } 
    } 

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

在我看來,我呈現形式和轉儲錯誤消息

... 
<?php echo $form->renderForm(false); ?> 
... 
//render single elements here 
//eg. <?php echo $form->note->renderViewHelper(); ?> 
... 
    <?php var_dump($form->getMessages()) ?> 
... 

形式的每個驗證後,我得到這樣的錯誤消息的數組:

array(2) { ["note"]=> array(1) { ["isEmpty"]=> string(36) "Value is required and can't be empty" } ["no_csrf_foo"]=> array(1) { ["isEmpty"]=> string(36) "Value is required and can't be empty" } } 

如果我向元素填充了很好的值,最後一個錯誤總是用於標記 - NotEmpty,所以我的表單永遠不會有效。

+2

CSRF元素如何顯示在窗體中?你能編輯問題並添加CSRF令牌的HTML輸出嗎? – Benz 2015-02-24 09:39:36

+0

是的,問題是我沒有渲染令牌元素。我不使用我的表單中的裝飾器,所以我手動渲染視圖中的每個元素,所以我忘了呈現csrf標記。所以thx爲您的評論,這給了我的解決方案。 – porosman 2015-02-24 09:51:34

+0

不錯的發現:)。如果你回答自己的問題,你可以設置爲'已解決'應該照顧任何其他傳入用戶來回答這個問題:) – Benz 2015-02-24 09:57:15

回答

0

問題已解決。我沒有在我的視圖中渲染令牌元素,所以我添加到視圖:

<?php echo $form->no_csrf_foo->renderViewHelper(); ?>