将 "Validation Constraints" 添加到未附加到实体的表单

Add "Validation Constraints" to a form which is not attached to an entity

我在没有使用实体的情况下创建了以下表单 class

<?php
// src/OC/PlatformBundle/Form/AdvertType.php

namespace OC\PlatformBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class MyFormType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
      ->add('date',      'date')
      ->add('title',     'text')          
      ->add('save',      'submit')
    ;
  }

  public function setDefaultOptions(OptionsResolverInterface $resolver)
  {
    $resolver->setDefaults(array());
  }

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

我想添加一组验证约束来验证此表单。

您可以像这样添加约束:

$builder
    ->add('title', 'text', array(
        'constraints' => array(
            new \Symfony\Component\Validator\Constraints\NotBlank(['message' => 'Your error message']),
        )
    ));

文档在这里:http://symfony.com/doc/current/book/forms.html