Created
November 23, 2012 13:19
-
-
Save havvg/4135587 to your computer and use it in GitHub Desktop.
Dynamic validation_groups based on choice value
This file contains 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\CatchmentArea\Type; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\Form\FormInterface; | |
use Symfony\Component\OptionsResolver\OptionsResolverInterface; | |
use Ormigo\Bundle\OrmigoBundle\Form\CatchmentArea\DataTransformer\CatchmentAreaModelTransformer; | |
use Ormigo\Bundle\OrmigoBundle\Form\CatchmentArea\Extension\TypeChoiceList; | |
class CatchmentAreaType extends AbstractType | |
{ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
/* | |
* The validation groups are defined by the chosen type of CatchmentArea. | |
* | |
* We use the default validation of the respective form types. | |
* The avaiable choices for the type match the names of the form types. | |
* | |
* Only the selected child form will be set to validate. | |
*/ | |
$validationGroups = function(FormInterface $form) { | |
/* @var $data \Ormigo\Bundle\OrmigoBundle\Form\CatchmentArea\Model\CatchmentArea */ | |
$data = $form->getParent()->getViewData(); | |
if ($form->getName() === $data->type) { | |
return array('Default'); | |
} | |
return array(); | |
}; | |
$areaOptions = array( | |
'validation_groups' => $validationGroups, | |
'error_bubbling' => false, | |
); | |
$builder | |
->add('type', 'choice', array( | |
'choice_list' => new TypeChoiceList(), | |
'expanded' => true, | |
)) | |
->add('zipcode_area', 'zipcode_area', $areaOptions) | |
->add('ambit_area', 'ambit_area', $areaOptions) | |
->add('country_area', 'country_area', $areaOptions) | |
; | |
$builder->addModelTransformer(new CatchmentAreaModelTransformer()); | |
} | |
public function setDefaultOptions(OptionsResolverInterface $resolver) | |
{ | |
$resolver->setDefaults(array( | |
'data_class' => 'Ormigo\Bundle\OrmigoBundle\Form\CatchmentArea\Model\CatchmentArea', | |
'invalid_message' => 'catchment_area.invalid', | |
)); | |
} | |
public function getName() | |
{ | |
return 'catchment_area'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment