1

I have a dynamic form.

For exemple, if something, my form contains FormType1 else my form contains FormType2 or FormType3 ....

I would detect if my form is modify.
If my form is completed, I apply is valid() method and if there is an error I return in the form or if there is no error, I apply a redirection.
I know how to do that.

But, if my fom was submitted without modifications (with no new value) I want to apply an other redirection without validation because my validation will return false with required fields.

I can't test if all values are null because in form there may be combobox or boolean, or initial value, ...

I have a solution with javascript and two submit buttons.
If the value of button submit is 'just_redirection' I don't apply the validation else I apply validation.

Is there a way in Symfony2 (or full PHP) to know if the submitted form is the same that the initial form?

doydoy44
  • 5,720
  • 4
  • 29
  • 45
  • 1. Compare form data to database actual data, see if anything changed – RiggsFolly Sep 02 '16 at 08:21
  • 2. Put the original data in hidden fields and compare editable fields with hidden fields to see if anything has changed – RiggsFolly Sep 02 '16 at 08:22
  • @RiggsFolly, Thks for your suggestions, those are good ideas. But for each case (form1, form2, ...) I should do apply a specifique code, that I don't want, I just want to know if there is a generic method to know if a form is modified. I I don't have a answer, may be I will code your second solution with a generic way – doydoy44 Sep 02 '16 at 08:30

1 Answers1

1

Let's assume your form is bound with an entity MyEntity, in your controller you need to copy your original object, let the form handle the request, then compare your objects:

public function aRouteAction(Request $request, MyEntity $myEntity)
{
    $entityFromForm = clone $myEntity;
    // you need to clone your object, because since PHP5 a variable contains a reference to the object, so $entityFromForm = $myEntity wouldn't work

    $form = $this->createForm(new MyFormType(), $entityFromForm);
    $form->handleRequest($request);

    if($entityFromForm == $myEntity) {
        // redirect when no changes
    }

    if($form->isValid()) {
        // redirect when there are changes and form submission is valid
    }
    else {
        // return errors
    }
}

For object cloning please refer to the php manual.

Peter Featherstone
  • 7,835
  • 4
  • 32
  • 64
lolmx
  • 521
  • 6
  • 18
  • Thks for your reply. I like this idea, so +1 :). I use the [CraueFormFlowBundle](https://github.com/craue/CraueFormFlowBundle) with modifications, so I will try this to validate – doydoy44 Sep 02 '16 at 08:56
  • You're welcome. If it doesn't apply to your use case, please add your form and controller code in your question and leave a comment ;) – lolmx Sep 02 '16 at 09:05