Search code examples
javascriptsymfony-formsconfirmation

Confirm before pressing submit form in symfony and javascript


I am have a form built with FormBuilderInterface. My code looks:

$builder->add('Save',
      SubmitType::class,
            [
                'label' => 'button.save',
                'onSubmit'=> 'return validate()'],
            ]
        );

and my validate looks:

function validate() {
        if (document.getElementById("status").value === "published") {
            return confirm('Are you sure?');
        }
    }

How to prevent saving a form if in confirmation I select cancel? Looks like confirm doesn't work for me.


Solution

  • Try this out. You have to return false to prevent form from submiting.

    function validate() {
      if (document.getElementById("status").value === "published") {
        return confirm('Are you sure?');
      } else {
        console.log('Not Ready');
        return false;
      }
    }
    <form action="https://www.google.com" onsubmit="return validate()">
    
      <input id="status">
    
      <button type="submit">Submit</button>
    
    </form>