0% found this document useful (0 votes)
34 views

Symfony Forms

Form types in Symfony can represent individual form fields, groups of fields, or entire forms. The form builder allows describing form fields using a fluent interface. Form views represent forms in the template and include additional view-specific information. The form factory retrieves type definitions and uses them to configure form builders and views. It can be extended to add features like request handling, CSRF protection, templating, and validation.

Uploaded by

riversoto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Symfony Forms

Form types in Symfony can represent individual form fields, groups of fields, or entire forms. The form builder allows describing form fields using a fluent interface. Form views represent forms in the template and include additional view-specific information. The form factory retrieves type definitions and uses them to configure form builders and views. It can be extended to add features like request handling, CSRF protection, templating, and validation.

Uploaded by

riversoto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

forms

Definiciones
Form Type

In other projects, it’s common to differentiate between “forms” and “form fields”. In Symfony,
all of them are “form types”:
a single <input type="text"> form field is a “form type” (e.g. TextType );
a group of several HTML fields used to input a postal address is a “form type” (e.g.
PostalAddressType );
an entire <form> with multiple fields to edit a user profile is a “form type” (e.g.
UserProfileType ).
https://symfony.com/doc/current/forms.html#form-types

FormBuilder

“form builder” object allows you to describe the form fields using a fluent interface.

FormView

Is the view representation of a form.


This means that you never deal with Form instances in the template, but with
FormView instances.
These store additional, view-specific inforrmation, such as HTML names, IDs and so on.

FormFactory
A form factory retrieves the type hierarchy from the loaded extensions and uses them to
configure new FormBuilder and FormView objects.
Las Forms son objetos construidos por la form factory.
Se puede crear una factory fácilmente $formFactory = Forms::createFormFactory();
Esa factory es básica puede crear forms básicas, pero le falta soporte para:
Request Handling. (se puede usar el componente Httpfoundation , ejemplo
$formFactory = Forms::createFormFactoryBuilder()-
>addExtension(new HttpFoundationExtension())-
>getFormFactory(); )
CSRF protection. (Protection against CSRF attacks is built into the Form component, but
you need to explicitly enable it or replace it with a custom solution.)
Templating. (se puede usar el componente Twig )
Translation. (se puede usar componente Translation )
Validation (Se puede usar el componente Validation .

Architecture

https://webmozart.io/blog/2012/03/06/symfony2-form-architecture/

Abstraction: providing suitable data structures for describing and reusing your code. (conversiones
back and forth)

Extensibility:

Specialization: a simple example is to extend [the above] date selector to also show selectors for
the time.

Mixins: Mixins, on the other hand, allow to attach functionality to existing objects without the
need to specialize them. Example: change all existing fields to include an asterisk (“*”) in their
label if they require user input.

Nota: In object-oriented programming languages, a mixin (or mix-in) is a class that


contains methods for use by other classes without having to be the parent class of those
other classes. How those other classes gain access to the mixin’s methods depends on
the language. The Core extension provides all field definitions (called form types)
implemented by the framework.Mixins are sometimes described as being “included”
rather than “inherited”.

En PHP se pueden usar Traits


https://stackoverflow.com/questions/6876925/is-it-possible-to-use-mixins-in-php

<?php
class Base {
public function sayHello() {
echo 'Hello ';
}
}

trait SayWorld {
public function sayHello() {
parent::sayHello();
echo 'World!';
}
}

class MyHelloWorld extends Base {


use SayWorld;
}

$o = new MyHelloWorld(); The Core extension provides all


field definitions (called form types) implemented by the
framework.
$o->sayHello();
?>
Composionality (Composite design pattern)
No existe diferencia entre forms y fields funcionalemnte hablando. Todos
Aceptan valores desde el modelo.
Convierten el valor a una representacion para ser vista.
render HTML.
Aceptan valores enviados por el usuario.
Convierten valores de vuelta al formato del modelo.
Opcionalmente hacen validación.
Separation on concerns:
Data Transformation
HTML Generation (the View)
Validation
Data Mapping
Model Binding
1. reuse existing metadata during form construction in order to reduce duplication of code and
configuration
2. read default values from a domain object (an instance of Profile) and write the submitted values
back into the object
Dynamic Behavior
Disntintos campos en base a elecciones.

Forms High level architecture (symfony 2)

uses Symfony2’s Event Dispatcher internally for processing events.

The Core extension provides all field definitions (called form types que según lo de arriba son las forms
y form fields) implemented by the framework.
The Validation extension integrates the Symfony2 Validator to implement form validation.
The DI extension adds support for Symfony2’s Dependency Injection component.
The CSRF extension adds CSRF protection to forms.
The Doctrine 2 extension (shipped with the Doctrine bridge) adds a Doctrine-specific drop down field
and provides components that let forms know about Doctrine metadata

Forms Low level architecture (symfony 2)

A form and all of its children can be represented by the same data structure that implements the Composite
pattern (como un árbol).

The main implementation of FormInterface is the class Form , which uses three components to
do its work:

A data mapper distributes the data of a form to its children and merges the data of the children
back into the form’s data. (para abajo y para arriba)
Two chains of data transformers convert values between different representations.
An event dispatcher allows you to execute custom code at predefined points during form
processing.

Esos tres se pasan al constructor mediante FormConfigInterface . Because the constructor


signature is quite long and complicated, a form builder simplifies the construction of Form instances.

As can be seen in the diagram, a form has three different representations throughout its
lifecycle:
During construction, it is represented by a hierarchy of FormBuilder objects.
In the controller, it is represented by a hierarchy of Form objects.
In the view, it is represented by a hierarchy of FormView objects.

Because the configuration of form builders and form views is repetitive, Symfony2 implements form
types that group such configuration.

Form types support dynamic inheritance.


Mixins, as described before, are supported in Symfony2 by so-called type extensions.
https://symfony.com/doc/current/form/create_form_type_extension.html Form type extensions
are incredibly powerful: they allow you to modify any existing form field types across the entire
system.

You might also like