2016-11-09 15 views
0

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!' 
      )), 
     ) 
    )); 

呼び出すときは、(それがあなたのBlogPostTypeを使用してフォームタイプです)、親フォームから、このタイプのrequired => trueを設定する必要があり

答えて

0

ありがとう:

$formBuilder->add('whatever', BlogPostType::class, ['required' => true]); 

また、あなたが設定することができrequired = trueBlogPostTypeの既定値:

+0

私は自分のコードを更新し、それが – phpmeter

+0

@jlacsonph仕事doesntのあなたは、私が上記の書いたものを実装する方法を投稿することができますか? – martin

+0

こんにちは、私の更新されたコードをもう一度チェックしてください、ありがとうございます。 – phpmeter

1

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; 
+0

を参照してください私のソースコードを更新し、それdoesntの仕事 – phpmeter

+0

''constraints' => new NotBlank'に間違っています。 Constraintsキーは配列でなければなりません。私の例で慎重に見てください –

+0

私の更新されたコードをもう一度チェックしてください、ありがとうございます – phpmeter

関連する問題