douchuilai2355 2014-08-27 12:15
浏览 15
已采纳

在isValid之后的zf2表单绑定

I just moved from zf1 to zf2 and some simple task are giving me a headache. I have some filters on my form. Filters are being run on form isValid function andafter this function been run, I expected filtered data to be rebind to the form.

I an using zend framework 2.2.7

This is my controller code:

<?php

namespace Test\Controller;

use Test\Entity\Product;
use Test\Form\CreateProduct;
use Zend\Mvc\Controller\AbstractActionController;

class TestController extends AbstractActionController
{

    public function indexAction()
    {
      $form = new CreateProduct();
         $product = new Product();
         $form->bind($product);

         $request = $this->getRequest();
         if ($request->isPost()) {
             $form->setData($request->getPost());

             if ($form->isValid()) {
                 var_dump($product);
             }
             $form->bind($product); // manual rebind seems to work but look hackish 

         }

         return array(
             'form' => $form,
         );
    }
}
  • 写回答

1条回答 默认 最新

  • dongwen5351 2014-08-28 13:25
    关注

    if you like to "rebind" the data back to the form (after the validation fail) use $form->populateValues()

    $request = $this->getRequest();
    if( $request->isPost() )
    {
        if( $form->isValid() )
        {
            $validatedFormData = $form->getData();
            // do something
    
        } else {
    
            // populate posted values to form
            $form->populateValues($request->getPost());
    
            // fetch form errors $form->getMessages()
            // whatever
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?