abraham63
abraham63

Reputation: 443

Symfony form Constraints CallBack 2 parameters

I am trying to add a constraint with 2 parameters in my Symfony but i don't succeed. My code :

The form field I am trying to check if definied like that :

  ->add(
                self::CUSTOMER_FAMILY_CUSTOMFIELD_FIELD_NAME,
                'text',
                array(
                  'constraints' => array(
                      new Constraints\Callback(
                          array(
                              'methods' => array(
                                  array(
                                      $this, 'checkField'
                                  )
                              )
                          )
                      )
                  ),
                    'required' => true,
                    'empty_data' => false,
                    'label' => self::trans('Some number'),
                    'label_attr' => array(
                        'for' => 'customfield'
                    ),
                    'mapped' => false,
                )
            )

Don't care about variable in capital letter it's Thelia CMS variable which are well defined.

Then my function checkField if defined like that :

public function checkField($field, ExecutionContextInterface $context)
    {
  if(strlen($field)!=0)$context->addViolation(self::trans('FIELD ERROR')}

This is working fine. Then I would like to add a second parameters in my constraint which is a Thelia CMS object ($event). But I don't find how to do that with this code structure.

Any help is welcome.

Upvotes: 0

Views: 437

Answers (1)

Bernardin EBASSA
Bernardin EBASSA

Reputation: 81

As I see your issue, I can see these possible cases:

  1. Your $event object does not depend on the CUSTOMER_FAMILY_CUSTOMFIELD_FIELD_NAME field value:

In this case, you can just set your $event object as an attribute of the class containing your checkField function, and use its value in the function.

  1. The $event object depends on the value of the field:

In this case, you can just do the same as previous, and then, set you $event attribute in a form event callback, where you'll also redefine the field so that it's updated at the desired form event.

Upvotes: 0

Related Questions