Created
December 17, 2012 13:58
-
-
Save havvg/4318463 to your computer and use it in GitHub Desktop.
Symfony2 Forms: dynamic "NotBlank"-constraints
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, thanks for the inspiration 👍