Wednesday, July 29, 2015

Symfony - Add custom validation and business logic checking

<?php
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Length;

use Symfony\Component\Form\FormError;

class ContactController extends Controllerl
{
  public function addAction(Request $request)
  {
    $formId = 'warranty-registration-form';
    $formDefault = array();
    $formAttr = array('attr' => array(
        'class' => $formId,
        #'files' => TRUE,
    ));

    $form = $this->createFormBuilder($formDefault, $formAttr)
    #$form = $this->get('form.factory')->createNamedBuilder($formId, 'form', $formDefault, $formAttr)
      ->add('name', 'text', array(
        'data' => 'another dummy name', // default value can be set from here, too.
        'label' => 'Your Name:',
        'attr' => array('maxlength' => 5),
        'required' => TRUE,
        'constraints' => array(
          new NotBlank(),
          new Length(array('min' => 3)),
          new Expression(['expression' => 'value >= 5 and value <= 10', 'message' => 'not a valid value']),
        )
      ))
      ->add('joindate', 'date')
      ->getForm();

    $form->handleRequest($request); // handleRequest() recognizes whether the form is submitted and writes the submitted data.

    if ($form->isSubmitted() === TRUE) {
      $status = FALSE;

      if ($form->get('name')->getData() === 'asdf') {
        $form->get('name')->addError(new FormError('this is a fake name'));
      }

      if ($form->isValid() === TRUE) {
        $status = TRUE;

        return new JsonResponse(array(
          'status' => $status,
        ));
      }
      else {
        $errors = array();

        foreach ($form->all() as $fieldName => $formField) {
          foreach ($formField->getErrors(true, true) as $error) {
            $errors[$fieldName][] = $error->getMessage();
          }
        }

        return new JsonResponse(array(
          'status' => $status,
          'errors' => $errors,
        ));
      }
    }
    else {
      return $this->render('DemoBundle:Contact:index.html.twig', array(
        'form' => $form->createView(),
      ));
    }
  }
}
?>

Reference:

http://symfony.com/doc/current/cookbook/validation/custom_constraint.html
http://api.symfony.com/2.7/Symfony/Component/Form/FormInterface.html#method_getData
http://symfony.com/doc/current/components/form/form_events.html

No comments: