Formularios y Validaciones

Richard Melo

@allucardster

Agenda

  • Qué es un Form?
  • Gestionar un Form
  • Clase Form
  • Validaciones

Qué es un Form?

"Es una librería independiente que permite a los usuarios finales interactuar con los datos de la aplicación"

Cómo crear un formulario?


$form = $this->createFormBuilder($product)
    ->add('name', 'text')
    ->add('price', 'number', array('precision' => 2))
    ->add('description', 'textarea')
    ->add('save', 'submit')
    ->getForm();

Como crear un formulario

// src/Acme/StoreBundle/Controller/DefaultController.php
 
// ...
use Acme\StoreBundle\Entity\Product;
use Symfony\Component\HttpFoundation\Response;
// ...

public function newAction()
{
    $product = new Product();

    $form = $this->createFormBuilder($product)
        ->add('name', 'text')
        ->add('price', 'number', array('precision' => 2))
        ->add('description', 'textarea')
        ->add('save', 'submit')
        ->getForm();
    
    return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
        'form' => $form->createView(),
    ));
}
//...

Renderizar un formulario

{# src/Acme/StoreBundle/Resources/views/Default/new.html.twig #}
 
{{ form(form) }}

Renderizar un formulario

{# src/Acme/StoreBundle/Resources/views/Default/new.html.twig #}
 
{{ form_start(form) }}
    {{ form_errors(form) }}
 
    {{ form_row(form.task) }}
    {{ form_row(form.dueDate) }}
 
    {{ form_rest(form) }}
 
{{ form_end(form) }}

Como crear un formulario sin una entidad

// src/Acme/StoreBundle/Controller/DefaultController.php
 
// ...
use Acme\StoreBundle\Entity\Product;
use Symfony\Component\HttpFoundation\Response;
// ...

public function newAction()
{
    $product = array(
        'name' => '',
        'price' => 0.0,
        'description' => ''
    );

    $form = $this->createFormBuilder($product)
        ->add('name', 'text')
        ->add('price', 'number', array('precision' => 2))
        ->add('description', 'textarea')
        ->add('save', 'submit')
        ->getForm();
    
    return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
        'form' => $form->createView(),
    ));
}
//...

Procesar un formulario

// src/Acme/StoreBundle/Controller/DefaultController.php
 
// ...
use Acme\StoreBundle\Entity\Product;
use Symfony\Component\HttpFoundation\Response;
// ...

public function newAction()
{
    $product = new Product();

    $form = $this->createFormBuilder($product)
        ->add('name', 'text')
        ->add('price', 'number', array('precision' => 2))
        ->add('description', 'textarea')
        ->add('save', 'submit')
        ->getForm();
    
    $form->handleRequest($request);
 
    if ($form->isValid()) {
        // guardar el producto en la base de datos
 
        return $this->redirect($this->generateUrl('product_success'));
    }
    
    return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
        'form' => $form->createView(),
    ));
}
//...

Formulario y Asociaciones

// src/Acme/StoreBundle/Controller/DefaultController.php
 
// ...
use Acme\StoreBundle\Entity\Product;
use Acme\StoreBundle\Entity\Category;
use Symfony\Component\HttpFoundation\Response;
// ...

public function newAction()
{
    $product = new Product();

    $form = $this->createFormBuilder($product)
        ->add('name', 'text')
        ->add('price', 'number', array('precision' => 2))
        ->add('description', 'textarea')
        ->add('category', 'entity', array(
            'class' => 'AcmeStoreBundle:Category',
            'property' => 'name',
        ))
        ->add('save', 'submit')
        ->getForm();
    
    $form->handleRequest($request);
 
    if ($form->isValid()) {
        // guardar el producto en la base de datos
 
        return $this->redirect($this->generateUrl('product_success'));
    }
    
    return $this->render('AcmeStoreBundle:Default:new.html.twig', array(
        'form' => $form->createView(),
    ));
}
//...

Tipos de campos

Campos de texto

  • text
  • textarea
  • email
  • integer
  • password

Tipos de campos

Campos de selección

  • choice
  • entity

Tipos de campos

Campos de fecha

  • date
  • datetime
  • time

Tipos de campos

Otros 

  • checkbox
  • file
  • radio

Acción y método en un Form

// src/Acme/StoreBundle/Controller/DefaultController.php
 
// ...
use Acme\StoreBundle\Entity\Product;
use Acme\StoreBundle\Entity\Category;
use Symfony\Component\HttpFoundation\Response;
// ...

public function newAction()
{
    //...
    $form = $this->createFormBuilder($product)
        ->setAction($this->generateUrl('create_product'))
        ->setMethod('GET')
        ->add('name', 'text')
        ->add('price', 'number', array('precision' => 2))
        ->add('description', 'textarea')
        ->add('category', 'entity', array(
            'class' => 'AcmeStoreBundle:Category',
            'property' => 'name',
        ))
        ->add('save', 'submit')
        ->getForm();
    //...
}
//...

Acción y método en un Form

{# src/Acme/StoreBundle/Resources/views/Default/new.html.twig #}
{{ form(form, {'action': path('create_route'), 'method': 'GET'}) }}

Clase Form

// src/Acme/StoreBundle/Form/Type/ProductType.php
namespace Acme\StoreBundle\Form\Type;
 
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
 
class ProductType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text')
            ->add('price', 'number', array('precision' => 2))
            ->add('description', 'textarea')
            ->add('category', 'entity', array(
                'class' => 'AcmeStoreBundle:Category',
                'property' => 'name',
            ))
            ->add('save', 'submit')
        ;
    }
 
    public function getName()
    {
        return 'product_form';
    }
 
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\StoreBundle\Entity\Product',
        ));
    }
}
// src/Acme/StoreBundle/Controller/DefaultController.php
 
// ...
use Acme\StoreBundle\Entity\Product;
use Acme\StoreBundle\Entity\Category;
use Symfony\Component\HttpFoundation\Response;
// ...

public function newAction()
{
    $product = new Product();

    $form = $this->createForm(new ProductType(), $product);
    //...
}
//...
// src/Acme/StoreBundle/Controller/DefaultController.php
 
// ...
use Acme\StoreBundle\Entity\Product;
use Acme\StoreBundle\Entity\Category;
use Symfony\Component\HttpFoundation\Response;
// ...

public function newAction()
{
    $product = new Product();

    $form = $this->createForm(new ProductType(), $product, array(
        'action' => $this->generateUrl('create_product'),
        'method' => 'GET',
    ));
    //...
}
//...

Validaciones

Crear validaciones

# Acme/StoreBundle/Resources/config/validation.yml
Acme\TaskBundle\Entity\Product:
    properties:
        name:
            - NotBlank: ~
        price:
            - NotBlank: ~
            - Range:
                min: 0
                max: 180
        description:
            - NotBlank: ~
            - Length:
                min: 1
                max: 255

Crear validaciones

// src/Acme/StoreBundle/Entity/Product.php
//...
use Symfony\Component\Validator\Constraints as Assert;

class Product
{
    //...
    /**
     * @ORM\Column(type="string", length=100)
     * @Assert\NotBlank()
     */
    protected $name;
 
    /**
     * @ORM\Column(type="decimal", scale=2)
     * @Assert\NotBlank()
     * @Assert\Range(min=0, max=180)
     */
    protected $price;
 
    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     * @Assert\Length(min=1, max=255)
     */
    protected $description;
}

Grupos de validación

# Acme/StoreBundle/Resources/config/validation.yml
Acme\TaskBundle\Entity\Product:
    properties:
        name:
            - NotBlank: { groups: [registration] }
        price:
            - NotBlank: { groups: [registration] }
            - Range:
                min: 0
                max: 180
        description:
            - NotBlank: { groups: [registration] }
            - Length:
                min: 1
                max: 255

Grupos de validación

// src/Acme/StoreBundle/Entity/Product.php
//...
use Symfony\Component\Validator\Constraints as Assert;

class Product
{
    //...
    /**
     * @ORM\Column(type="string", length=100)
     * @Assert\NotBlank(groups={'registration'})
     */
    protected $name;
 
    /**
     * @ORM\Column(type="decimal", scale=2)
     * @Assert\NotBlank(groups={'registration'})
     * @Assert\Range(min=0, max=180)
     */
    protected $price;
 
    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank(groups={'registration'})
     * @Assert\Length(min=1, max=255)
     */
    protected $description;
}

Grupos de validación

// src/Acme/StoreBundle/Controller/DefaultController.php
 
// ...
use Acme\StoreBundle\Entity\Product;
use Acme\StoreBundle\Entity\Category;
use Symfony\Component\HttpFoundation\Response;
// ...

public function newAction()
{
    $product = new Product();

    $form = $this->createForm(new ProductType(), $product, array(
        //...
        'validation_groups' => array('registration'),
    ));
    //...
}
//...

Preguntas?

Muchas Gracias

Made with Slides.com