Last active
February 23, 2016 22:58
-
-
Save rdohms/4565419 to your computer and use it in GitHub Desktop.
Adding Validation Errors in an array without a data_class. On line 64 and 68 i tried both `addViolationAtSubPath` and `addViolationAtPath` to get the error to show on the relative fields, but they always show at top of form. How can i do this?
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 MyProject\Bundle\WebBundle\Form; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\OptionsResolver\OptionsResolverInterface; | |
use Symfony\Component\Validator\Constraints\Callback; | |
use Symfony\Component\Validator\Constraints\NotBlank; | |
use Symfony\Component\Validator\ExecutionContext; | |
use Symfony\Component\Validator\Constraints\Date; | |
class ExtraDataType extends AbstractType | |
{ | |
/** | |
* {@inheritdoc} | |
* | |
* @param \Symfony\Component\Form\FormBuilderInterface $builder | |
* @param array $options | |
*/ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
parent::buildForm($builder, $options); | |
$builder | |
->add('name', 'text', array( | |
'required' => true | |
) | |
) | |
->add('choicefield', 'choice', array( | |
'required' => true, | |
'expanded' => true, | |
'choices' => array( | |
'a' => 'A', | |
'b' => 'B', | |
'c' => 'C' | |
) | |
) | |
) | |
->add('field1', 'text', array( | |
'required' => false | |
) | |
) | |
->add('field2', 'text', array( | |
'required' => false | |
) | |
); | |
} | |
/** | |
* @param OptionsResolverInterface $resolver | |
*/ | |
public function setDefaultOptions(OptionsResolverInterface $resolver) | |
{ | |
$proceeds = new Callback(array( | |
function($data, ExecutionContext $context) { | |
if ($data['choicefield'] == 'c') { | |
if ( ! isset($data['field1']) || empty($data['field1'])){ | |
$context->addViolationAtSubPath('field1', 'Required!!', array(), null); | |
} | |
if ( ! isset($data['field2']) || empty($data['field2'])){ | |
$context->addViolationAtSubPath('field2', 'Required!!', array(), null); | |
} | |
} | |
} | |
)); | |
$resolver->setDefaults(array( | |
'constraints' => array($proceeds) | |
)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A little tip for debugging such errors faster in the future:
var_dump($violation->getPropertyPath())
)var_dump((string)$form->get('myField')->getPropertyPath())
)Note the difference.
I'll be working on something to facilitate this somewhen.