dqhdz04240 2015-05-14 12:08 采纳率: 0%
浏览 58

Symfony2 - 自定义验证不启动

I have a form with multiple date fields. I need to check if eventStop < eventStart (date fields). IF it's true, $form->isValid() should stop script and put errors on page. So according to http://symfony.com/doc/current/cookbook/validation/custom_constraint.html#constraint-validators-with-dependencies I've create new custom validation constraint but when I submit the form, my validation is not execute, script skips it...

My code: MyBundle\Validator\Constraints\EventFormFieldsValidator.php

namespace MyBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ORM\EntityManager;

/**
 * @Annotation
 */
class EventFormFieldsValidator extends ConstraintValidator {

    private $em;

    public function __construct(EntityManager $em) {
        $this->em = $em;
    }

    public function validate($object, Constraint $constraint) {
        die('end'); /* just for check  */
        $this->context->addViolationAt('eventStart', 'There is already an event during this time!');
        $this->context->addViolation('There is already an event during this time!');
    }

}

MyBundle\Validator\Constraints\EventFormFields.php

namespace MyBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class EventFormFields extends Constraint {

    public function validatedBy() {
        return 'event_form_validator';
    }

    public function getTargets() {
        return self::CLASS_CONSTRAINT;
    }

}

MyBundle\Entity\Event.php

namespace MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use MyBundle\Validator\Constraints as ValidateAssert;

/**
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="MyBundle\Entity\EventRepository")
 * @ORM\Table(name="events")
 * @ValidateAssert\EventFormFields
 * 
 */
class Event {
    ....

MyBundle\Resources\config\services.yml

services:
    validator.unique.my_form_validator:
        class: MyBundle\Validator\Constraints\EventFormFieldValidator
        arguments:
            - "@doctrine.orm.entity_manager"
        tags:
            - { name: validator.constraint_validator, alias: event_form_validator }

app\Resources\config\services.yml

imports:
    - { resource: "@MyBundle/Resources/config/services.yml" }

MyBundle\Forms\EventFormType.php

namespace MyBundle\Forms;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;


class EventFormType extends AbstractType {

    public function getName() {
        return 'c_event';
    }

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('eventName', 'text', array(
                    'label' => 'Event name',
                    'attr'=> array('class'=>'input-sm')
                ))
                ->add('location', 'text', array(
                    'label' => 'Location',
                    'attr'=> array('class'=>'input-sm')
                ))
                ->add('description', 'textarea', array(
                    'label' => 'Description',
                    'attr'=> array('class'=>'input-sm')
                ))
                ->add('eventStart','collot_datetime', array(
                    'label' => 'Event start',
                    'attr'=> array('class'=>'input-sm'),
                    'pickerOptions' => [
                        'format' => 'yyyy-mm-dd hh:ii:00',
                        'weekStart' => 1,
                        'autoclose' => true,
                        'keyboardNavigation' => true,
                        'language' => 'en',
                        'minuteStep' => 5,
                        'pickerReferer ' => 'default', //deprecated
                        'pickerPosition' => 'bottom-right',
                    ]
                ))
                ->add('eventStop','collot_datetime', array(
                    'label' => 'Event end',
                    'attr'=> array('class'=>'input-sm'),
                    'pickerOptions' => [
                        'format' => 'yyyy-mm-dd hh:ii:00',
                        'weekStart' => 1,
                        'autoclose' => true,
                        'keyboardNavigation' => true,
                        'language' => 'en',
                        'minuteStep' => 5,
                        'pickerReferer ' => 'default', //deprecated
                        'pickerPosition' => 'bottom-right',
                    ]
                ))
                ->add('eventSignUpEndDate','collot_datetime', array(
                    'label' => 'Sign up until',
                    'attr'=> array('class'=>'input-sm'),
                    'pickerOptions' => [
                        'format' => 'yyyy-mm-dd hh:ii:00',
                        'weekStart' => 1,
                        'autoclose' => true,
                        'keyboardNavigation' => true,
                        'language' => 'en',
                        'minuteStep' => 5,
                        'pickerReferer ' => 'default', //deprecated
                        'pickerPosition' => 'bottom-right',
                    ]
                ))
                ->add('maxGuests','integer', array(
                    'label' => 'Max guests',
                    'required' => false,
                    'attr'=> array(
                                'placeholder'   => 'Empty for unlimited',
                                'class' => 'input-sm'
                            )
                ))
                ->add('latitude','text', array(
                    'label' => 'Latitude',
                    'attr'=> array(
                            'class'=>'input-sm',
                        )
                ))
                ->add('longitude','text', array(
                    'label' => 'Longitude',
                    'attr'=> array(
                            'class'=>'input-sm',
                        )
                ))
                ->add('private','checkbox', array(
                        'label'    => 'Private',
                        'required' => false,
                ));
    }

    public function setDefaultOptions(\Symfony\Component\OptionsResolver\OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'MyBundle\Entity\Event',
            'validation_groups' => array('registration'),
        ));
    }

}
  • 写回答

1条回答 默认 最新

  • dqj5046 2015-05-14 13:14
    关注

    you need to add the validation group in the validation definition as follow:

    MyBundle\Entity\Event.php

    namespace MyBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    use MyBundle\Validator\Constraints as ValidateAssert;
    
        /**
         * @ORM\Entity
         * @ORM\Entity(repositoryClass="MyBundle\Entity\EventRepository")
         * @ORM\Table(name="events")
         * @ValidateAssert\EventFormFields(groups={"registration"})
         * 
         */
        class Event {
    

    Hope this help

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭