aWebDeveloper
aWebDeveloper

Reputation: 38352

One form two action

Hi i have a few form fields i want the on click of button a the control to be sent to action 1 but on click of button 2 it has to be sent to action 2. Currently i am using js to change the form action dynamically on click. but is there any other solution. I cant do the checking after submit in a same method thet have to be two different methods.

The 2 buttons in this case are view(html data needs to be displayed) and download(same data as csv file). I am using cakephp 1.2 but i feel this is more of a generic problem

Upvotes: 1

Views: 1722

Answers (3)

aWebDeveloper
aWebDeveloper

Reputation: 38352

HTML5 has a formaction attribute for this

<form action="/url" id="myForm">
     <input type="submit" value="save1" formAction="/url1" />
     <input type="submit" value="save2" formAction="/url2" />
</form>

Here is a fallback if you need it.

if (!('formAction' in document.createElement('input'))){
 $('form').on('click', 'input[type=submit]', function (e) {
    var attr = this.getAttribute('formAction');

    if (attr) {
        this.action = attr; //Set the form's action to formAction
    }
  });
}

Upvotes: 0

aWebDeveloper
aWebDeveloper

Reputation: 38352

I found out there are few solutions

  1. Regular JavaScript to change th form action on click of the buttons
  2. AJAX to send the data to two separate actions on click of separate buttons
  3. As suggested by deceze to do the processing on server side(which was not easily possible in my case)

Upvotes: 0

deceze
deceze

Reputation: 522024

One form can only have one action. This is a limitation of HTML. To work around it on the client-side, you need Javascript.

It sounds like the better idea would be to give each submit button a distinctive name and value. This will be submitted like other form elements, so you can detect in the Controller which button was clicked. From there it should only be a matter of switching some View logic in the controller between normal output and download.

Upvotes: 3

Related Questions