【问题标题】:symfony form not coming back valid, do i have form object issues?symfony 表单没有返回有效,我有表单对象问题吗?
【发布时间】:2015-03-04 22:25:53
【问题描述】:

我尝试了各种方法,但我无法让表单返回isValid(),所以我想先确保这部分是正确的。

    <?php
    namespace ABC\DeBundle\Controller;

    use Symfony\Bundle\FrameworkBundle\Controller\Controller,
        Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
        Sensio\Bundle\FrameworkExtraBundle\Configuration\Template,
        Sensio\Bundle\FrameworkExtraBundle\Configuration\Method,
        Symfony\Component\HttpFoundation\Request,
        Symfony\Component\HttpKernel\Exception\HttpException,
        Symfony\Component\Form\FormBuilderInterface,
        Symfony\Component\Form\Forms,
        Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension,
        Symfony\Component\Form\Extension\Validator\ValidatorExtension,
        Symfony\Component\Validator\Validation,
        Symfony\Component\Validator\Constraints\Length,
        Symfony\Component\Validator\Constraints\NotBlank,
        Symfony\Component\Config\Definition\Exception\Exception,
        Symfony\Component\HttpFoundation\Response,
        ABC\CoreBundle\Controller\CoreController;

    class DoSomethingController extends CoreController

{

    protected $debug = FALSE;

    public function doSomethingAction(Request $request)
    {
        /**
         * build the form here
         *
         * Either use out custom build form object
         * $form = $formFactory->createBuilder('form', $defaultData)
         *
         * Or alternatively, use the default formBuilder
         * $form = $this->createFormBuilder($defaultData)
         */
        $validator = Validation::createValidator();

        $formFactory = Forms::createFormFactoryBuilder()
            ->addExtension(new HttpFoundationExtension())
            ->addExtension(new ValidatorExtension($validator))
            ->getFormFactory();

        $defaultData = array(
            'comment' => 'Type your comment here',
            'name' => 'Type your name here',
            'resources' => '{}',
            'warning' => 'Warning, your still in debug mode on your controller.php'
        );

        //$form = $this->createFormBuilder($defaultData)
        $form = $formFactory->createBuilder('form', $defaultData)
            ->setAction($this->generateUrl('do_something'))
            ->add("emails", 'text', array(
                'label' => "Recipient's email address (separate with a comma)",
                'constraints' => array(// constraints here
                ),
            ))
            ->add('comment', 'textarea', array(
                'label' => "Leave a comment",
            ))
            ->add('name', 'text', array(
                'label' => "Your name",
                'constraints' => array(// constraints here
                ),
            ))
            ->add('email', 'email', array(
                'label' => "Your email address",
                'constraints' => array(// constraints here
                ),
            ))
            ->add('copy', 'checkbox', array(
                'label' => "Send me a copy",
                'required' => false,
            ))
            ->add('cancel', 'button', array(
                'label' => "Cancel",
                'attr' => array('class' => 'btn-branded'),
            ))
            ->add('save', 'submit', array(
                'label' => "Email Resources",
                'attr' => array('class' => 'btn-branded'),
            ));

        //make resources visible by putting them into a text box
        $resourceInputType = $this->debug ? 'text' : 'hidden';
        $form->add('resources', $resourceInputType, array(
            'constraints' => array(// constraints here
            ),
        ));

        //add a visible warning input box, so we know were on debug, we don't want this released to live on debug.
        $this->debug ? ($form = $form->add('warning', 'text')) : null;

        $form .= $form->getForm();

        //alternatively
        //$form->bind($_POST[$form->getName()]);
        //$form->handleRequest($request);

        //validate
        if ($form->isValid()) {

            $data = $form->getData();

            //run some data checks, then fire it off
            $something = $this->DoSomething($data);
            return $something;
            //$return=array("responseCode"=>200,  "data"=>$data);
            // $return=json_encode($return); //json encode the array
            // return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
        }else
    {
        echo '<pre>';
        var_dump('form is coming back as not isValid(), make sure debug is off, heres our errors list:<br>');
        var_dump($form->getErrorsAsString());
        echo '</pre>';
    }

        //its not a POST, or  POST is invalid, so display the form
        return $this->render($this->someTemplate, array(
            'form' => $form->createView(),
        ));
    }
}

1) 在条件操作期间传递此表单对象的过程中,我有点困惑(明智的做法)。在操作它时我是否需要连接它或者 symfony 提供什么来避免这种情况,或者我只是错误地传递对象?请参阅此示例以更好地理解此问题。例如$form .= $form-&gt;getForm(); 在操作过程中我如何正确连接这个表单对象,就像我使用三元组时所做的那样,让自己相信当我传递这个对象时,它是同一个对象,而不是一个新对象。

2) 发现任何其他可能导致损坏的问题?

编辑 @Chausser 这是最新的代码,简化了一点,我现在正在使用这里http://api.symfony.com/2.5/Symfony/Component/Form/Forms.html 找到的一些明显罕见的例子。它仍然没有回来isValid()。请比较我以前和新的表单对象用法示例。

 <?php
 /**
  * @param Request $request
  * @Route("/do/something", name="do_something",  options={"expose"=true})
  * @Method({"GET", "POST"})
  * @return mixed
  */
public function doSomethingAction(Request $request)
{
    $defaultData = array(
        'comment' => 'Type your comment here',
        'name' => 'Type your name here',
        'resources' => '{}',
        'warning' => 'Warning, your still in debug mode on your controller.php'
    );

    $resourceInputType = $this->debug ? 'text' : 'hidden';

    $formFactory = Forms::createFormFactory();
    $form = $formFactory
        ->createBuilder()
        ->setAction($this->generateUrl('do_something'))
        ->add("emails", 'text', array(
            'label' => "Recipient's email address (separate with a comma)",
            'constraints' => array(// constraints here
            ),
        ))
        ->add('comment', 'textarea', array(
            'label' => "Leave a comment",
        ))
        ->add('name', 'text', array(
            'label' => "Your name",
            'constraints' => array(// constraints here
            ),
        ))
        ->add('email', 'email', array(
            'label' => "Your email address",
            'constraints' => array(// constraints here
            ),
        ))
        ->add('copy', 'checkbox', array(
            'label' => "Send me a copy",
            'required' => false,
        ))
        ->add('cancel', 'button', array(
            'label' => "Cancel",
            'attr' => array('class' => 'btn-branded'),
        ))
        ->add('save', 'submit', array(
            'label' => "Email Resources",
            'attr' => array('class' => 'btn-branded'),
        ))
        ->add('resources', $resourceInputType, array(
            'constraints' => array(// constraints here
            ),
        ))
        ->getForm();

    $form->handleRequest($request);

    //validate
    if ($form->isValid()) {

        $data = $form->getData();

    //run some data checks, then fire it off
        $something = $this->DoSomething($data);
        return $something;
    //other options for returning
    //$return=array("responseCode"=>200,  "data"=>$data);
    // $return=json_encode($something); //json encode the array
    // return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
    } else {
        echo '<pre>';
        var_dump('form is coming back as not isValid(), make sure debug is off, heres our errors list:<br>');
        var_dump($form->getErrorsAsString());
        echo '</pre>';
    }

    //its not a POST, or  POST is invalid, so display the form
    return $this->render($this->someTemplate, array(
        'form' => $form->createView(),
    ));
}

编辑 所以现在在我编辑后让表单不尝试停止请求,除非它的 POST 请求,而不是 GET 请求

    if($request && $request->getMethod() == 'POST'){

    $form->handleRequest($request);

    //validate
    if ($form->isValid()) {

        $data = $form->getData();

        //run some data checks, then fire it off
        $something = $this->DoSomething($data);
        return $something;
        //other options for returning
        //$return=array("responseCode"=>200,  "data"=>$data);
        // $return=json_encode($something); //json encode the array
        // return new Response($return,200,array('Content-Type'=>'application/json'));//make sure it has the correct content type
    } else {
        echo '<pre>';
        var_dump('form is coming back as not isValid(), make sure debug is off, heres our errors list:<br>');
        var_dump($form->getErrorsAsString());
        echo '</pre>';
    }
}

导致下面提到的控制器错误

【问题讨论】:

  • 我以前从未见过这个 $form .= $form-&gt;getForm() 用于 OOP。 .= 仅用于字符串的连接分配
  • 好的,到目前为止一切都很好,所以我不会那样做,只有字符串?有道理,难怪我很久没用mcu了,它只是为了演示目的,所以你可以看到问题区域之一,那么正确的方法是什么?即有人可以向我保证,如果我这样做$form = $form-&gt;getForm();,那就是它继续我在上面制作的对象,而不是得到一个新的空白表格或其他东西......或者我应该每次我都将它设置为一个新变量操纵它?
  • 我不完全理解您遇到的错误?将$form .= $form-&gt;getForm(); 更改为$form = $form-&gt;getForm();(无点)。然后取消注释$form-&gt;handleRequest($request);这行你应该有一个工作,如果没有那么你需要查看表单错误,原因是$errorsArray = $form-&gt;getErrors(true);
  • 好的,谢谢。我一直在测试的是$form-&gt;getForm(),当我尝试这种方式(哈哈)它不是字符串时,我确实收到了一条明确的错误消息。然后我已经添加了handleRequest,错误返回为空,我已经试过了。所以我可能做错了那部分。生病添加一些代码,看看这是否可能是问题的一部分。
  • 获取表单的错误,if($form-&gt;isValid()){...} else{ var_dump($form-&gt;getErrors(true)) }

标签: forms validation symfony post


【解决方案1】:

好吧,看起来好像验证器扩展在使用时被破坏了,因为没有包含 HttpFoundationExtension()。显然要使用验证器或工厂构建器(不确定哪个)也需要此扩展。

工作示例,从初始示例复制,添加了工作部分。

    <?php
namespace ABC\DeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller,
    Sensio\Bundle\FrameworkExtraBundle\Configuration\Route,
    Sensio\Bundle\FrameworkExtraBundle\Configuration\Template,
    Sensio\Bundle\FrameworkExtraBundle\Configuration\Method,
    Symfony\Component\HttpFoundation\Request,
    Symfony\Component\HttpKernel\Exception\HttpException,
    Symfony\Component\Form\FormBuilderInterface,
    Symfony\Component\Form\Forms,
    Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension,
    Symfony\Component\Form\Extension\Validator\ValidatorExtension,
    Symfony\Component\Validator\Validation,
    Symfony\Component\Validator\Constraints\Length,
    Symfony\Component\Validator\Constraints\NotBlank,
    Symfony\Component\Config\Definition\Exception\Exception,
    Symfony\Component\HttpFoundation\Response,
    ABC\CoreBundle\Controller\CoreController;

class DoSomethingController extends CoreController
{
    protected $debug = FALSE;

    public function doSomethingAction(Request $request)
    {
        $validator = Validation::createValidator();
        $builder = Forms::createFormFactoryBuilder()
            ->addExtension(new ValidatorExtension($validator))
            ->addExtension(new HttpFoundationExtension());


        $defaultData = array(
            'comment' => 'Type your comment here',
            'name' => 'Type your name here',
            'resources' => '{}',
            'warning' => 'Warning, your still in debug mode on your controller.php'
        );

        $resourcesInputType = $this->debug ? 'text' : 'hidden';

        $form = $builder->getFormFactory()
            ->createBuilder('form', $defaultData)
            ->setAction($this->generateUrl('do_something'))
            ->add("emails", 'text', array(
                'label' => "Recipient's email address (separate with a comma)",
                'constraints' => array(// constraints here
                ),
            ))
            ->add('comment', 'textarea', array(
                'label' => "Leave a comment",
            ))
            ->add('name', 'text', array(
                'label' => "Your name",
                'constraints' => array(// constraints here
                ),
            ))
            ->add('email', 'email', array(
                'label' => "Your email address",
                'constraints' => array(// constraints here
                ),
            ))
            ->add('copy', 'checkbox', array(
                'label' => "Send me a copy",
                'required' => false,
            ))
            ->add('cancel', 'button', array(
                'label' => "Cancel",
                'attr' => array('class' => 'btn-branded'),
            ))
            ->add('save', 'submit', array(
                'label' => "Email Resources",
                'attr' => array('class' => 'btn-branded'),
            ))->add('resources', $resourcesInputType, array(
                'constraints' => array( // constraints here
                ),
            ))
            ->getForm()
            ->handleRequest($request);


        if ($form->isValid()) {

            $data = $form->getData();

            //run some data checks, then fire it off
            $something = $this->DoSomething($data);
            return $something;
        }
        // initial render
        return $this->render($this->someTemplate, array(
            'form' => $form->createView(),
        ));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 2016-07-06
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    相关资源
    最近更新 更多