Symfony2 form_errors

后端 未结 4 768
情书的邮戳
情书的邮戳 2021-02-06 14:51

I think its a simple question. Its about outputting errors. This is my twig file:

    
{{ form_label(form.d
4条回答
  •  别那么骄傲
    2021-02-06 15:21

    Here is my solution. I have decided to create an array with errors and pass it into the view (twig). It took me a while to work out how to get error messages... but here we go:

        // Controller example: 
        public function indexAction(Request $request)
        {
        $task = new \Michael\MikeBundle\Entity\Task();
        $task->setTask('Write a blog post');
        $task->setDueDate(new \DateTime('tomorrow'));
        
        $form = $this->createFormBuilder($task)
             ->add('task', 'text', 
                     array('attr' => array('title' => 'Enter Task')))
             ->add('dueDate', 'date', array(
                 'widget' => 'single_text',
                 'required' => false,
                 'attr' => array('title' => 'Insert due date')))
             ->getForm();
    
        // If user submitted code
        if ($request->getMethod() == 'POST') {
                // Get form part from request
                $request->request->get('form');    
                
                // Bind request into the form
                $form->bindRequest($request);
            }
            
        // Pass into the view
        return array('errors' => $this->_getErrors($form), 'form' => $form->createView());
        }
    
        protected function _getErrors($form)
        {
        // Validate form
        $errors = $this->get('validator')->validate($form);
        
        // Prepare collection
        $collection = array();
        
        // Loop through each element of the form
        foreach ($form->getChildren() as $key => $child) {
            $collection[$key] = "";
        }
        
        foreach ($errors as $error) {
            $collection[str_replace("data.", "", $error->getPropertyPath())] = $error->getMessage();
        }
        return $collection;
        }
    

    The important part is method _getErrors($form) as it returns an array like this (if there are errors)

    $errors['task'] = This value should not be blank

    $errors['dueDate'] = ""

    And here is twig part:

        
    {{ form_label(form.dueDate) }} {{ form_widget(form.dueDate) }} {{ errors[form.dueDate.vars["name"]] }}
    {{ form_label(form.task) }} {{ form_widget(form.task) }} {{ errors[form.task.vars["name"]] }}

    I hope its clear enough. Let me know if you need help.

    Please post answer if there is an easier way to do it.

提交回复
热议问题