在回调中添加Symfony Assert

时间:2017-01-16 09:56:38

标签: validation symfony callback assert

我,当其他属性等于某个东西时,我必须向属性添加一个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
    }
}

所以,如果角色等于3,我想检查患者是否是轻微的(有断言或其他情况)。这是怎么做的?

1 个答案:

答案 0 :(得分: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)其他方式 - 在您的实体中进行自定义验证回调并在那里使用直接断言。我认为这是可能的。

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

希望这对你有所帮助。