Home | About Me
| | | | | | | | | |

Symfony 3: Forms

Hands-On | 02 Oct 2017
Tags: symfony, ready, form, form-class, validation, formbuilder


The code-snippets in this article are obtained from: https://symfony.com/doc/current/forms.html

1) Installation

composer require symfony/form

2) Building form in controller

task;
    }

    public function setTask($task)
    {
        $this->task = $task;
    }

    public function getDueDate()
    {
        return $this->dueDate;
    }

    public function setDueDate(\DateTime $dueDate = null)
    {
        $this->dueDate = $dueDate;
    }
}
setTask('Write a blog post');
        $task->setDueDate(new \DateTime('tomorrow'));

        $form = $this->createFormBuilder($task)
            ->add('task', TextType::class)
            ->add('dueDate', DateType::class)
            ->add('save', SubmitType::class, array('label' => 'Create Task'))
            ->getForm();

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // $form->getData() holds the submitted values
            // but, the original `$task` variable has also been updated
            $task = $form->getData();

            // ... perform some action, such as saving the task to the database
            // for example, if Task is a Doctrine entity, save it!
            // $entityManager = $this->getDoctrine()->getManager();
            // $entityManager->persist($task);
            // $entityManager->flush();

            return $this->redirectToRoute('task_success');
        }

        return $this->render('default/new.html.twig', array('form' => $form->createView(),));
    }
}
{# templates/default/new.html.twig #}
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

{# 
form_start - renders the start tag of the form, with enctype
form_widget - fields, validation errors
form_end - eng tag of the form + automatic CSRF protection
#}

start($form) ?>
widget($form) ?>
end($form) ?>

3) Validation

composer require symfony/validator

Annotation is used for validation

task;
    }

    /**
     * @param string $task
     */
    public function setTask($task): void
    {
        $this->task = $task;
    }


    /**
     * @return \DateTime
     */
    public function getDueDate(): \DateTime
    {
        return $this->dueDate;
    }

    /**
     * @param \DateTime $dueDate
     */
    public function setDueDate(\DateTime $dueDate): void
    {
        $this->dueDate = $dueDate;
    }
}
{# templates/default/new.html.twig #}
{{ form_start(form, {'attr': {'novalidate': 'novalidate'}}) }} 
{{ form_widget(form) }} 
{{ form_end(form) }}

Symfony Field Types

https://symfony.com/doc/current/reference/forms/types.html

Passing options to Fields

->add('dueDate', DateType::class, array(
    'widget' => 'single_text',
    'required' => true // applies client-side validation if enabled,
    'label' => 'Due Date',
))
->add('task', null, array('attr' => array('maxlength' => 4)))

Creating Form Class

add('task')
            ->add('dueDate', null, ['widget' => 'single_text'])
            ->add('agreeTerms', CheckboxType::class, ['mapped' => false])
            ->add('save', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        // indicates the type of class which holds data
        $resolver->setDefaults([
            'data_class' => Task::class
        ]);
    }
}
setTask("Here is the new task");
        $task->setDueDate(new \DateTime('tomorrow'));

        $form = $this->createForm(TaskType::class, $task);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $task = $form->getData();

            echo $form->get('agreeTerms')->getData();

            return $this->redirectToRoute('task_success');
        }

        return $this->render('task/new.html.twig', [
            'form' => $form->createView()
        ]);
    }
}