2017-01-16 2 views
0

저는 다른 atribute가 무엇인가와 같을 때 공물에 Assert를 추가해야합니다. 이처럼 : 어떻게이 작업을 수행 할 역할은 3보다 동일한 경우 환자가 (다른 어설 또는 일도 포함) 미성년자 인 경우Symfony Assert를 콜백에 추가하십시오.

/** 
* @Assert\Callback(methods={"isChildMinor",) 
*/ 
class PatientData 
{ 
/** 
* @Assert\Date() 
*/ 
public $birthday; 

public $role; 

public function isChildMinor(ExecutionContext $context) 
{ 
    if ($this->role == 3 && check @assert\isMinor() to $birtday) { 
    =>add violation 
    } 
} 

그래서, 내가 확인하려면?

답변

2

몇 가지 방법으로 원하는 것을 할 수 있습니다.

1) 양식에서 바로 만들 수 있습니다. 마찬가지로 :

use Symfony\Component\Validator\Constraints as Assert; 

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $yourEntity = $builder->getData(); 
    //here you start the field, you want to validate 
    $fieldOptions = [ 
    'label'  => 'Field Name', 
     'required' => true, 
    ]; 
    if ($yourEntity->getYourProperty != 'bla-bla-bla') { 
    $fieldOptions[] = 'constraints' => [ 
     new Assert\NotBlank([ 
      'message' => 'This is unforgivable! Fill the field with "bla-bla-bla" right now!', 
     ]), 
    ], 
    } 
    $builder->add('myField', TextType::class, $fieldOptions); 

2) 다른 방법은 Entity에서 사용자 정의 유효성 검사 콜백을 만들고 거기에 직접 어설 션을 재생하는 것입니다. 가능하다고 생각합니다.

3) 그러나 내 관점에서 볼 때 최적의 방법은 유효성 검사 그룹에 여러 개의 어설 션을 사용하는 것입니다. 생일 필드에 Assert \ isMinor (groups = { "myCustomGroup"})를 지정해야합니다. 그리고, 당신의 형태 :

public function configureOptions(OptionsResolver $resolver) 
{ 
    $resolver->setDefaults([ 
    'validation_groups' => function (FormInterface $form) { 
     $yourEntity = $form->getData(); 
     if ($yourEntity->role !== 3) { 
      return ['Default', 'myCustomGroup']; 
     } 
     return ['Default']; 
    }, 

희망이 당신을 위해 도움이 될 것입니다.

+0

나는 그것을 시험해보고, 고마워. 고마워. – NicolaPez

+0

안녕하세요,이 구현하려면 노력하고있어, 한 가지 문제가 있습니다. 내가 이해하지 못하는 것들이 'myCustomGruop'반환 할 유효성 검사를 얻는 방법입니다. 나는이 같은 어설 마이너을 지정 /** * @Assert \ 날짜() * @Assert \ 초과] ("- 십팔년") */ 공공 $ 생일; 그래서 어떻게 반환 배열에 넣어 모르겠다. – NicolaPez

+0

이 http://symfony.com/doc/current/components/options_resolver.html과 그룹 유효성 확인으로 이제는 모두 잘 작동합니다. 도와 주셔서 감사합니다 – NicolaPez