0

我试图用 Symfony 创建一个表单,但我收到一个错误:

您不能在未绑定的表单上调用 isValid()。

  1. 我有带有注释和 Doctrine 的类 User 保存在数据库中。类 User 具有使用 Doctrine 生成的 getter 和 setter。

  2. 我有 UserTye.php:

    <?php
    
    namespace Iftodi\DesignBundle\Form;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilder;
    
    class UserType extends AbstractType
    {
    
        public function buildForm(FormBuilder $builder, array $options)
        {
            $builder->add('name');
            $builder->add('username');
            $builder->add('email','email');
            $builder->add('password','password');
    
        }
    
        public function getName()
        {
            return "userRegister";
        }
    }
    
    ?>
    
  3. 在控制器中:

    function registerAction()
    {
        $user = new User();
        $form = $this->createForm(new UserRegister(),$user);
    
        $request = $this->getRequest();
    
        if($request->getMethod() == 'POST')
            $form->bindRequest ($request);
    
        if($form->isValid())
        {
    
        }
    
        return $this->render("IftodiDesignBundle:User:register.html.twig", 
                array('form' => $form->createView())
                );
    }
    
4

2 回答 2

4

如果你有一个发布请求,你只绑定你的表单,但总是调用 isValid 。正如消息所说:如果它没有被绑定,你就不能。像这样重新组织您的代码:

if ("POST" === $request->getMethod()) {
    $form->bindRequest($request);

    if ($form->isValid()) {
    }
}
于 2012-06-21T03:55:13.650 回答
1

梅林的回答是正确的。

这是代码的更新片段:对于 Symfony 2.1+

if ('POST' === $request->getMethod()) {
    $form->bind($request);

    if ($form->isValid()) {
        // do something with $form
    }
}

参考:http ://symfony.com/blog/form-goodness-in-symfony-2-1#no-more-bindrequest

如果您不在控制器中而是在 twig 扩展中,您可以通过您的服务注入声明传递请求堆栈在您的包中的 services.yml 中(注意 Symfony 2.4 版本)。

参考:http ://symfony.com/doc/current/book/service_container.html#injecting-the-request

services:
  your_service_name:
     class: YourBundle\YourTwigExtension
     arguments: [@request_stack]

然后在你的扩展

namespace YourBundle;

use Symfony\Component\HttpFoundation\RequestStack;

class YourTwigExtension extends \Twig_Extension
{
   private $request;

   public function __construct(RequestStack $request_stack)
   {
       $tmp_request = $request_stack->getCurrentRequest();
       if ($tmp_request) 
       {
          $this->request = $tmp_request;
       }
   }

   // add your filter/function/extension name declarations ...       

   public function yourFancyMethod()
   {
        if($this->request)
        {
             if ('POST' === $this->request->getMethod()) 
             {
                  $form->bind($this->request);

                  if ($form->isValid()) 
                  {
                      // do something with $form
                  }
             }
        }
   }

}
于 2014-01-21T00:34:55.550 回答