繁体   English   中英

无法使用没有data_class的表单使用Callback断言

[英]Unable to use Callback assert with a form without data_class

我正在创建一个名为IntervalType的自定义FormType。 我的IntervalType将有两个字段, startend并且类型为integer。 此自定义FormType将始终在没有data_class情况下data_class

我想添加一个约束来保证start低于end

如何在没有data_class的FormType中直接使用Symfony \\ Component \\ Validator \\ Constraints \\ Callback?

这是我的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(),
                ),
            ))
        );
    }
}

当表单不使用任何data_class时,唯一的选项似乎是Callback约束。

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();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM