Skip to content

Instantly share code, notes, and snippets.

@rdohms
Last active February 23, 2016 22:58
Show Gist options
  • Save rdohms/4565419 to your computer and use it in GitHub Desktop.
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?
<?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)
));
}
}
@rdohms
Copy link
Author

rdohms commented Jan 18, 2013

The answer is: [field1]

@webmozart
Copy link

A little tip for debugging such errors faster in the future:

  • Log the property path of the error you are interested in in ViolationMapper:38 (e.g. var_dump($violation->getPropertyPath()))
  • Log the property path of the field you would like it to be attached (e.g. var_dump((string)$form->get('myField')->getPropertyPath()))

Note the difference.

I'll be working on something to facilitate this somewhen.

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