Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
29 views

Simple Form Widgets: Retrouvez-Nous Sur Www. Ou Sur Notre WWW

This document provides information about Symfony form components including: 1) It describes common form fields like text, textarea, checkbox, file upload, entity, collection and embedded forms that can be used to build forms. 2) It explains how to create form classes and bind them to entities, as well as associate forms with validation rules. 3) It shows how forms can be rendered in Twig templates and customized with form themes to control their HTML output and styling. In 3 sentences, this document covers the main aspects of building forms in Symfony - including defining fields, associating forms with entities, validating form data, and rendering forms for display.

Uploaded by

losus007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Simple Form Widgets: Retrouvez-Nous Sur Www. Ou Sur Notre WWW

This document provides information about Symfony form components including: 1) It describes common form fields like text, textarea, checkbox, file upload, entity, collection and embedded forms that can be used to build forms. 2) It explains how to create form classes and bind them to entities, as well as associate forms with validation rules. 3) It shows how forms can be rendered in Twig templates and customized with form themes to control their HTML output and styling. In 3 sentences, this document covers the main aspects of building forms in Symfony - including defining fields, associating forms with entities, validating form data, and rendering forms for display.

Uploaded by

losus007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Form Sheets

Agence Web - iPhone & iPad Apps - Experts Symfony

Simple Form Widgets


<?php Widget Parent Common Options
/** Build a form */ * data_class, required, read_only, disabled, max_length, pattern, property_path, mapped,
$form = $this->createFormBuilder()->add('name')->getForm(); by_reference, label, attr, label_attr, translation_domain
text field
/** Bild a form linked to an entity */
textarea text
$form = $this->createFormBuilder($people)->add('name')->getForm();
password text always_empty
checkbox field value
Form Class radio checkbox
file field
<?php choice field multiple, expanded, choices, preferred_choices, empty_value
class ProductType extends AbstractType
hidden field
{
public function buildForm(FormBuilderInterface $builder, array $options) number field precision, grouping, rounding_mode
{ money field precision, grouping, divisor, currency
$builder->add('name', 'text'); percent field precision, type
} datetime field input, model_timezone, view_timezone, format, date_format, widget, date_widget,
time_widget, with_seconds, by_reference
public function getName()
{ birthday date years
return 'product'; date field years, months, days, widget, input, format, model_timezone, view_timezone, by_reference
} time field hours, minutes, seconds, widget, input, with_seconds, model_timezone, view_timezone,
} by_reference
locale choice

One to Many Relation language choice


country choice
timezone choice
<?php
$builder->add('category', 'entity', array( entity
'class' => 'Demo\\MyBundle\\Entity\\Category' url text default_protocol
)); repeated type, options, first_options, second_options, first_name, second_name
collection allow_add, allow_delete, prototype, prototype_name, type, options

Many to Many Relation email


search
text
text
integer field precision, grouping, rounding_mode
<?php
$builder->add('tags', 'entity', array(
'class' => 'Demo\\MyBundle\\Entity\\Tag',
'multiple' => true,
TWIG
'expanded' => true
));
Form Rendering

<form action="{{ path('store') }}" method="post" {{ form_enctype(form) }}>

Embed Form {{ form_widget(form) }}


<input type="submit" />
</form>
<?php
$builder->add('category', new CategoryType()); Form Template

{# src/Acme/StoreBundle/Resources/views/Default/index.html.twig #}
Embed Collection <form action="{{ path('store') }}" method="post" {{ form_enctype(form) }}>
{{ form_errors(form) }}

<?php {{ form_row(form.name) }}
// Elao\DemoBundle\Entity\Contact {{ form_row(form.price) }}
class Contact
{ {{ form_rest(form) }}
public $phones = array();
<input type="submit" />
public function __construct() </form>
{
$this->phones = array(new Phone(), new Phone(), new Phone()); Embed Form
}
} {{ form_row(form.price) }}

<?php <h3>Category</h3>
// Elao\DemoBundle\Entity\Phone <div class="category">
class Phone {{ form_row(form.category.name) }}
{ </div>
public $number;
} {{ form_rest(form) }}

Form Theming
<?php
// Elao\DemoBundle\Form\PhoneType {# src/Elao/BlogBundle/Resources/public/views/Form/fields.html.twig #}
$builder->add('number', 'text'); {% block form_row %}
{% spaceless %}
<?php <div class="form_row">
// Elao\DemoBundle\Form\ContactType {{ form_label(form) }}
$builder->add('phones', 'collection', array( {{ form_errors(form) }}
'type' => new PhoneType() {{ form_widget(form) }}
)); </div>
{% endspaceless %}
{% endblock form_row %}
Binding
{# src/Elao/BlogBundle/Resources/public/views/show.html.twig #}
<?php {% form_theme form 'ElaoBlogBundle:Form:fields.html.twig'}
public function newAction()
{
$request = $this->getRequest(); OR
if ('POST' === $request->getMethod()) {
$form->bind($request); # app/config/config.yml
if ($form->isValid()) { twig:
// treatment form:
} resources: ['ElaoBlogBundle:Form:fields.html.twig']
}
}

Retrouvez-nous sur www.elao.com ou sur notre blog www.elao.org


Form Sheets

Agence Web - iPhone & iPad Apps - Experts Symfony

Validation Callback Constraints


YML File <?php
// src/Acme/BlogBundle/Entity/Author.php
# src/Elao/DemoBundle/Resources/config/validation.yml
use Symfony\Component\Validator\Constraints as Assert;
Elao\DemoBundle\Entity\Thing:
use Symfony\Component\Validator\ExecutionContext;
properties:
foobar:
/**
- NotBlank
* @Assert\Callback(methods={"isAuthorValid"})
getters:
*/
tokenValid:
class Author
- True: { message: "The token is invalid" }
{
private $firstName;
Annotations
public function isAuthorValid(ExecutionContext $context)
<?php
{
class Thing
// somehow you have an array of "fake names"
{
$fakeNames = array();
/**
* @Assert\NotBlank
// check if the name is actually a fake name
*/
if (in_array($this->getFirstName(), $fakeNames)) {
protected $foobar;
$context->addViolationAtSubPath('firstname', 'Error', array(), null);
}
/**
}
* @Assert\True(message={"The token is invalid"})
}
*/
public function isTokenValid()
{
return $this->token == $this->generateToken(); Validation Groups
}
} <?php
// src/Acme/BlogBundle/Entity/User.php
PHP namespace Acme\BlogBundle\Entity;

<?php use Symfony\Component\Security\Core\User\UserInterface;


use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Constraints\NotBlank;
class User implements UserInterface
class Thing {
{ /**
public static function loadValidatorMetadata(ClassMetadata $metadata) * @Assert\Email(groups={"registration"})
{ */
$metadata->addPropertyConstraint('foobar', new NotBlank()); private $email;
$metadata->addGetterConstraint('tokenValid', new True(array(
'message' => 'The token is invalid', /**
))); * @Assert\NotBlank(groups={"registration"})
} * @Assert\MinLength(limit=7, groups={"registration"})
} */
private $password;

Constraints /**
* @Assert\MinLength(2)
All */
private $city;
Blank message
}
Callback methods
Choice choices, callback, multiple, strict, min, max, message, multipleMessage, minMessage, maxMessage // with the validator component
Collection fields, allowExtraFields, allowMissingFields, extraFieldsMessage, missingFieldsMessage $errors = $validator->validate($author, array('registration'));
Count minMessage, maxMessage, exactMessage, min, max
Country message // inside a Form class
Date message use Symfony\Component\OptionsResolver\OptionsResolverInterface;
DateTime message
public function setDefaultOptions(OptionsResolverInterface $resolver)
Email message, checkMX, checkHost {
False message $resolver->setDefaults(array(
File maxSize, mimeTypes, ... 'validation_groups' => array('registration')
));
Image mimeTypes, minWidth, maxWidth, maxHeight, minHeight, ...
}
Ip version, message
Language message
Length maxMessage, minMessage, exactMessage, max, min, charset Create custom constraints
Locale message
NotBlank message Constraint Class
NotNull message <?php
Null message use Symfony\Component\Validator\Constraint;
Range minMessage, maxMessage, invalidMessage, min, max
/**
Regex message, pattern, htmlPattern, match
* @Annotation
Time message */
True message class Foobar extends Constraint
Type message, type {
Url message, protocols public $message = 'This value should be "foobar"';
}

Constraint Validator

<?php
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class FoobarValidator extends ConstraintValidator


{
public function validate($value, Constraint $constraint)
{
if ($value !== 'foobar') {
$this->context->addViolation($constraint->message);
return false;
}

return true;
}
}

Retrouvez-nous sur www.elao.com ou sur notre blog www.elao.org

You might also like