symfony表单没有回复有效,我有表单对象问题吗?

时间:2015-03-04 22:25:53

标签: forms validation symfony post

我尝试了各种各样的方式,但我无法回复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)在条件操作期间传递此表单对象的方式上我有点困惑(oop wise)。我是否需要在操作时将其连接起来,或者symfony提供什么来避免这种情况,或者我只是将对象传递给错误的?看这个例子来更好地理解这个问题。例如$form .= $form->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(),
    ));
}

修改 所以现在我的编辑后得到表单不尝试和haldne请求,除非它的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>';
    }
}

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

1 个答案:

答案 0 :(得分:0)

好吧,看起来好像验证器扩展名在使用时正在破坏,因为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(),
        ));
    }
}