表单类型类=> TestFormType.php
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
class TestFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name',
TextType::class,
[
'required' => true
]
)
->add('gender',
TextType::class,
[
'required' => true
]
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'ApiBundle\Entity\Test',
'csrf_protection' => false,
'validation_groups' => [ 'test' ]
));
}
}
实体=> test.php的
/**
* @var string
*
* @ORM\Column(name="name", type="string", nullable=true, length=10, options={"comment" : "Name"})
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="gender", type="string", nullable=true, length=10, options={"comment" : "Gender"})
* @Assert\Choice(choices = {"true", "false"}, message = "Choose a valid option.", groups={"test"})
*/
private $gender;
我想为需要的字段添加条件。在注释中。字段值空白允许但字段必须在请求中可用。
有可能的方法吗?
答案 0 :(得分:1)
“required”选项与元素在HTML页面中的呈现方式有关,与验证无关(参见http://symfony.com/doc/current/reference/forms/types/form.html#required)。它在API中没有意义。
如果要允许它为false或空字符串但不为null,则应在验证中使用NotNull约束(http://symfony.com/doc/current/reference/constraints/NotNull.html)。