Friday, March 4, 2022

[FIXED] Symfony2 form validation with html5 and CANCEL button

Issue

I have a contact form on Symfony2 where I put some validators as email, minLength etc. All those fields are also set as notBlank.

Due to this, HTML5 is also validating those fields (for the email and not blank), which is fine for me.

I have a submit button:

<input type="submit" value="Submit"/>

The problem is that I have another submit button which is a Cancel button:

<input name="cancel" type="submit" value="Cancel" />

With this button, in my controller I am doing a redirect:

if( $request->get('cancel') == 'Cancel' )
    return  $this->redirect($this->generateUrl('SciForumVersion2Bundle_homepage'));

Now, due to the HTML5 validation, I can't redirect because the fields are empty for example.

To reslove that, I have found two solutions, but I don't like them:

  1. Disable the HTML 5 validation:

    <form novalidate>
    
  2. Use JavaScript

But as I said, I don't like those methods and I am sure that there are some nice Symfony methods to resolve that.

Any idea? Thank you very much.


Solution

i resume my comment :)

when dealing with form (HTML5 or not) and you want to quit, you don't need to submit and validate any data You just have to put a simple href link to change the page. Use your favorite css style to have the same look

Tip: you could listen to javascript event "onbeforeunload" when user has changed an input value. It alerts the user that he will quit the page

Hope it helped !



Answered By - Julien Rollin

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.