2017-01-16 1 views
0

Ich muss eine Assert zu einem Attribut hinzufügen, wenn ein anderes Attribut gleich ist. Wie folgt aus:hinzufügen Symfony In einem Callback bestätigen

/** 
* @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 
    } 
} 

so, ich möchte überprüfen, ob der Patient Moll (mit assert oder Somethings sonst), wenn die Rolle als 3 gleich ist, wie dies zu tun?

Antwort

2

Es gibt mehrere Möglichkeiten zu tun, was Sie wollen.

1) Sie könnten es richtig im Formular machen. Wie folgt aus:

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) Andere Art und Weise - ist Ihre benutzerdefinierten Validierung Rückruf in Ihrer Entity zu machen und spielen mit direktem dort behauptet. Es ist möglich, denke ich.

3) Aber der optimale Weg, aus meiner Sicht - besteht darin, mehrere Behauptungen mit Validierungsgruppen zu verwenden. Sie müssen Assert \ isMinor (groups = {"myCustomGroup"}) im Geburtstagsfeld angeben. Und dann, in der Form:

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

Hope this würde für Dich hilfreich sein.

+0

ich werde das versuchen und Ihnen sagen, danke. – NicolaPez

+0

Hallo, ich versuche dies zu implementieren, ich habe ein Problem: Die Dinge, die ich nicht verstehe, ist, wie Sie die Validierung als "myCustomGruop" zurückgeben erhalten. Ich gebe die Assertion Minor wie folgt aus: /** * @Assert \ Date() * @Assert \ GreaterThan ("- 18 Jahre") */ public $ Geburtstag; so weiß ich nicht, wie in diesem Array zurückgeben. – NicolaPez

+0

ich verstehe mit dieser http://symfony.com/doc/current/components/options_resolver.html und die Gruppenvalidierung und jetzt funktioniert alles gut. Danke für die Hilfe – NicolaPez

Verwandte Themen