I\'m creating a form in Symfony2. The form only contains one book
field which allows the user to choose between a list of Books
entities. I need to c
Accepted answer did not work for me using Symfony Framework version 2.1. This is how I solved it.
class CustomConstraint extends Constraint
{
public $dependency;
public $message = 'The error message.';
}
class CustomConstraintValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (!$constraint->dependency->allows($value)) {
$this->context->addViolation($constraint->message);
}
}
}
class CustomFormType extends AbstractType
{
private $dependency;
public function __construct(Dependency $dependency)
{
$this->dependency = $dependency;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('field', 'type', array(
'constraints' => array(
new CustomConstraint(array('dependency' => $this->dependency))
)
));
}
}