0
votes

My app allows pieces of content to be saved to the database whilst status = draft. The form is made up of some fields that are required (e.g title) and then a bunch of other fields in a sub form that saves into a JSON array on the entity, alongside title.

I have validation constraints on the sub form fields, but don't want to enforce them if status = draft. In addition, I want to run the validation rules on form load so that the user knows what fields are required when the record moves to published, as this displays form errors but you can still save the form.

I've partly achieved this by, in my edit action, cloning the form and faking a submit on it. This generates the form errors. I can then render the cloned version with errors, but process and save the non-cloned version (to which I run $form->clearErrors(true) to effectively ignore validation when the status is draft)

It works but I wondered if there's a better way. I tried with FormEvents but couldn't achieve the validation on load.

1
Maybe custom validation based on execution context is what you need - ZloyPotroh
and use validation groups. - Frank B
Validation groups only appear to work on entity properties, not form fields (I effectively have lots of form fields saving to I've entity property). I did try a custom validator. It works but is more long winded than adding the constraints key to each form field - fistameeny

1 Answers

0
votes

Too big for a comment, so as an answer, but more like a bigger than comment idea ;)

As you have a Form made up of sub-Form objects, have considered making a Model object for each Form? That way you can make a matching validation group. You would not save the Model objects to the database.

It would allow you to also provide feedback to the user as you can validate each sub-Form separately for the Model objects.

Once a user saves the form without checking "Draft" (or the realy submit button, or however you've set this up), you catch that. When a User does this, you create a new Entity, you fill that with all data from all Model objects. You then create a new Validator instance and add to it all of the Validation Group's you created earlier.

You then run $validator->validate($entity, null, ['validation-group-model1', 'validation-group-model2']) (which is what happens internally anyway) and use the output to provide the user with the result.


Obviously, when editing existing Entity you need to populate all Model objects with data from the Entity.