Skip to content

Instantly share code, notes, and snippets.

@havvg
Created December 17, 2012 13:58
Show Gist options
  • Save havvg/4318463 to your computer and use it in GitHub Desktop.
Save havvg/4318463 to your computer and use it in GitHub Desktop.
Symfony2 Forms: dynamic "NotBlank"-constraints
<?php
namespace Ormigo\Bundle\OrmigoBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Ormigo\Bundle\OrmigoBundle\Form\DataTransformer\StreetAddressModelTransformer;
use Ormigo\Bundle\OrmigoBundle\Form\Validator\StreetAddressValidator;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
class StreetAddressType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$constraints = array(
'street' => array(),
'zipcode' => array(
new Regex(array(
'pattern' => '/\d{5}/',
'message' => 'street_address.zipcode.invalid',
)),
),
'city' => array(),
);
if ($options['required']) {
$constraints['street'] = array_merge(array(
new NotBlank(array(
'message' => 'street_address.street.required',
)),
), $constraints['street']);
$constraints['zipcode'] = array_merge(array(
new NotBlank(array(
'message' => 'street_address.zipcode.required',
)),
), $constraints['zipcode']);
$constraints['city'] = array_merge(array(
new NotBlank(array(
'message' => 'street_address.city.required',
)),
), $constraints['city']);
}
$builder
->add('street', 'text', array(
'label' => 'label.street',
'constraints' => $constraints['street'],
'autocomplete' => 'street-address',
))
->add('zipcode', 'text', array(
'label' => 'label.zipcode',
'constraints' => $constraints['zipcode'],
'attr' => array(
'pattern' => '\d{5}',
),
'autocomplete' => 'postal-code',
))
->add('city', 'text', array(
'label' => 'label.city',
'constraints' => $constraints['city'],
'autocomplete' => 'city',
))
;
$builder->addModelTransformer(new StreetAddressModelTransformer());
$builder->addEventSubscriber(new StreetAddressValidator());
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ormigo\Bundle\OrmigoBundle\Form\Model\Address',
'error_bubbling' => false,
'invalid_message' => 'street_address.invalid',
));
}
public function getName()
{
return 'street_address';
}
}
@mirague
Copy link

mirague commented Jun 25, 2014

Nice, thanks for the inspiration 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment