I am trying to validate an unbound field in my symfony2 form.
I have googled it and found several similar solutions, so I did a copy-paste and put my own stuff in th
CallbackValidator
FQCN should be Symfony\Component\Form\CallbackValidator
.
So, for anyone else needing validation for unbound form fields in symfony 2 here Is how I ended up doing it - turned out I was missing a bunch of use statements, they weren't listed on any of the sites where I found other threads on the subject.
I have weeded out everything but the essentials. Thanks to m2mdas for helping me along on this one.
<?php
namespace BizTV\UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\CallbackValidator;
use Symfony\Component\Form\FormValidatorInterface;
use Symfony\Component\Form\FormError;
use Doctrine\ORM\EntityRepository;
class newServerType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder->add('screenName', null, array('property_path' => false, 'label' => 'Namn på skärmen (användaren kan ändra det senare) '));
$builder-> addValidator(new CallbackValidator(function(FormInterface $form){
$screenName = $form->get('screenName')->getData();
if (empty($screenName)) {
$form['screenName']->addError(new FormError("Du måste ange ett namn för den nya skärmen"));
}
}));
}
public function getName()
{
return 'biztv_userbundle_newservertype';
}
}