如何在symfony2 PostType类中添加验证约束“Field is required”?有什么建议?我是SF2的新手,我只是编辑以前开发人员所做的工作。
use Symfony\Component\Validator\Constraints\NotBlank;
class BlogPostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$blogPostCategories = BlogPostCategoryQuery::create()
->filterByBlogPost($builder->getData())
->find();
$categoryIds = array();
foreach ($blogPostCategories as $blogPostCategory) {
$categoryIds[] = $blogPostCategory->getCategory()->getId();
}
$queryOptions = array(
'option_status' => Categorypeer::STATUS_ACTIVE,
'option_category_ids' => $categoryIds
);
$categories = CategoryQuery::create()
->filterActiveCategoriesByOptions($queryOptions)
->find();
$builder->add('category_ids', 'model', array(
'label' => 'Category',
'mapped' => false,
'class' => 'Deal\MainBundle\Model\Category',
'query' => CategoryQuery::create()
->filterActiveCategoriesByOptions()
->orderByName(),
'property' => 'name',
'empty_value' => 'Select categories',
'empty_data' => null,
'required' => true,
'multiple' => true,
'data' => $categories,
'constraints' => array(
new NotBlank(array(
'message' => 'Your message can not be blank! Ouch!'
)),
)
));
谢谢
答案 0 :(得分:0)
在调用时,您应该从父表单设置此类型的required => true
(这是使用BlogPostType
的表单类型):
$formBuilder->add('whatever', BlogPostType::class, ['required' => true]);
此外,您可以为required = true
默认设置BlogPostType
:
class BlogPostType extends AbstractType
{
// ...
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'required' => true
]);
}
}
答案 1 :(得分:0)
您可以使用constraints
键执行此操作。像这样:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('message', TextareaType::class, array(
'required' => true,
'constraints' => array(
new NotBlank(array(
'message' => 'Your message can not be blank! Ouch!'
)),
)
))
;
}
不要忘记添加用途:
use Symfony\Component\Validator\Constraints\NotBlank;