Невозможно использовать Callback assert с формой без data_class
Я создаю пользовательский FormType с именем IntervalType. Мой IntervalType будет иметь два поля, start
а также end
и будет иметь тип целое число. Этот пользовательский FormType всегда будет использоваться без data_class
,
Я хочу добавить ограничение, чтобы гарантировать, что start
ниже чем end
,
Как использовать Symfony\Component\Validator\Constraints\Callback напрямую в FormType без data_class
?
Вот мой IntervalType, просто для справки:
// src/AppBundle/Form/Type/IntervalType.php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Validator\Constraints\NotBlank;
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('start', IntegerType::class, array(
'constraints' => array(
new NotBlank(),
),
))
->add('end', IntegerType::class, array(
'constraints' => array(
new NotBlank(),
),
))
);
}
}
1 ответ
Когда форма не будет использовать какой-либо класс data_class, единственным вариантом будет ограничение обратного вызова.
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
class IntervalType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('start', IntegerType::class, array(
'constraints' => array(
new NotBlank(),
),
))
->add('end', IntegerType::class, array(
'constraints' => array(
new NotBlank(),
new Callback(array($this, 'validateInterval')),
),
))
->add('submit', SubmitType::class);
}
public function validateInterval($value, ExecutionContextInterface $context)
{
$form = $context->getRoot();
$data = $form->getData();
if ($data['start'] >= $value) {
$context
->buildViolation('The end value has to be higher than the start value')
->addViolation();
}
}
}