在回调中添加 Symfony 断言

add Symfony Assert in a Callback

我,当其他属性等于某个属性时,我必须向属性添加断言。像这样:

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

所以,如果角色等于 3,我想检查患者是否未成年人(使用 assert 或其他东西)。怎么做?

多种方式,随心所欲。

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) 其他方式 - 是在您的实体中进行自定义验证回调并在那里使用直接断言。我觉得有可能。

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'];
     },

希望对您有所帮助。