3

I have the following entity:

class Jobs {
//...

  /**
   * Tasks of Jobs
   * @var $tasks array
   */
   protected $tasks;

}

tasksis stored as Array in Json File like this:

[
  {
    "designation": "Task 1",
    "action": "Do action 1",
    //...
  },
  {
    "designation": "Task 2",
    "action": "Do action 2",
    //...
  },
  //...
]

When user define data from form, I would like to implement an assert for validation.

I'm implemented this one (I use yml):

...\Entity\Jobs:
  properties:
    tasks:
      - Collection:
        allowMissingFields: false
        missingFieldsMessage: jobs.tasks.missingfields
        fields:
          designation:
            - NotBlank:
              message: jobs.tasks.fields.blank
            ##...

When I try to validate form, I have a validation error for data.tasks[designation] and data.tasks[action].

Validation should be applied on second level of array.
How can I configure the validator for this kind of array?

1 Answer 1

7

The @Collection()-assertion is used when the array key is relevant, as is the case with each array representing a task. If you just care about the values in, e.g. a numerical array, you can use the @All()-constraint.

In your case you want to combine both, a list of tasks (@All) and each task (@Collection) inside that list. As annotation it could look something like this:

class Jobs
{
    /**
     * @Assert\All({
     *      @Collection(...)
     * })
     */
    private $tasks;
}

See: https://symfony.com/doc/current/reference/constraints/All.html

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer. It's exactly that.
What should be the type in the form? nothing? I mean we are creating the form in the controller, and we have a form for the Jobs class, and we have $builder->add... which has a second parameter we need to set, because this didn't work for me.
I think you are mixing up form elements with validation constraints. Assuming your Jobs are doctrine entities, then most likely you want an EntityType

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.