Form_For with Multiple Controller Actions for Submit

form_for with multiple controller actions for submit

There is not a simple Rails way to submit a form to different URLs depending on the button pressed. You could use javascript on each button to submit to different URLs, but the more common way to handle this situation is to allow the form to submit to one URL and detect which button was pressed in the controller action.

For the second approach with a submit buttons like this:

<%= form_for @people do |f| %>
# form fields here
<%= submit_tag "First Button", :name => 'first_button' %>
<%= submit_tag "Second Button", :name => 'second_button' %>
<% end %>

Your action would look something like this:

def create
if params[:first_button]
# Do stuff for first button submit
elsif params[:second_button]
# Do stuff for second button submit
end
end

See this similar question for more about both approaches.

Also, see Railscast episode 38 on multibutton forms.

How to have one form with multiple actions

You have some ways to do it, but all of the them require some javascript code.

The easiest I can think of is to dynamically change the form action when clicking each button (of type button, not submit which is the default), and then submit the form.

Example:

<form id="myform" name="myform" method="post" action="">
<input id="myinput" name="myinput" type="text"/>
[..]other inputs[/..]

<button type="button" onClick="deleteAction()">DELETE</button>
<button type="button" onClick="updateAction()">UPDATE</button>
<button type="button" onClick="saveAction()">SAVE</button>
</form>

Where the JS functions are:

function deleteAction() {
changeActionAndSubmit('/action/delete');
}

function updateAction() {
changeActionAndSubmit('/action/update');
}

function saveAction() {
changeActionAndSubmit('/action/save');
}

function changeActionAndSubmit(action) {
document.getElementById('myform').action = action;
document.getElementById('myform').submit();
}

Hope I got your doubt and that this solves your issue :)

Laravel Calling Multiple Controllers from Form Submit

Personally I would create a 'Logic' Directory as: app/Logic. Some people prefer Repositories etc, but this is my preference.
For your specific requirement I'd create the following file:

app/Logic/StudentLogic.php

StudentLogic

<?php

namespace App\Logic\StudentLogic;

use App\Student;
use App\LunchOrder;

class StudentLogic
{
public function handleStudentLunch(Request $request): bool
{
$student = Student::create(request(['firstname', 'lastname']));

if(is_null($student)) {
return false;
}

LunchOrder::create(array_merge(request(['lunch_value']), ['student_id' => $student->id]));

return true;
}
}

StudentController

public function store(Request $request)
{
$logic = new StudentLogic();

$valid = $logic->handleStudentLunch($request);
if($valid) {
return redirect('/students');
}
abort(404, 'Student Not Found');

}

ASSUMPTIONS

Student is stored under App/Student & LunchOrder is stored under App\LunchOrder
You will also need to use App\Logic\StudentLogic in StudentController

The reason I'd split this out into a Logic file is because I do not like 'heavy' controllers. Also, I'm not entirely sure what you're trying to acomplish here, but creating a student on the same request you create a LunchOrder seems like you're asking for trouble

How to use two different action methods in one form?

According to description, I suggest you could add another button to upload the file into the action method by using ajax instead of using form submit button.

You could add the upload button behind the uploadPop button and then using jquery ajax to upload.

More details, you could refer to below codes:

View:

 @* ... otherview codes*@
<input type="button" title="Ngarko dokument" name="ngarko" value="Ngarko" id="uploadPop" class="btn btn-info col-md-3" onclick="document.getElementById('file').click();" />
<input type="file" onchange="javascript:updateList()" multiple="multiple" style="display:none;" id="file" name="postedFiles" />
<input type="button" title= "UploadButton" name="ngarko2" value="Upload" id="upload" class="btn btn-info col-md-3" />

<div id="fileList"></div>
@* ... otherview codes*@

@section scripts{
<script>
$(function () {
$("#upload").click(function () {

var input = document.getElementById("file");
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("postedFiles", files[i]);
}

$.ajax(
{
url: "/NgarkoDokument/Dokument",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
alert("Files Uploaded!");
}
}
);
});
});
</script>

}

Result:

Sample Image

Actionmethod:
Sample Image

Passing form data to multiple actions in .NET

You can't really. You could potentially manufacture some JS solution that would switch out the action based on what button is clicked, but as far as a basic form goes, there's no way to change the action conditionally.

However, you can name your submit buttons and then branch within a single action. For example:

<button type="submit" name="SaveProgress">Save Current Progress</button>
<button type="submit" name="SaveFinal">Save Final Version</button>

Then, in your one action:

if (Request["SaveProgress"] != null)
{
// save progress
}
if (Request["SaveFinal"] != null)
{
// save final
}

Since only the button that is clicked will make it into the post data, you can use the presence of the button's name to determine which the user clicked.

One final option is to simply not worry about saving the incomplete data server-side. You can utilize localStorage to save the entered data as the user adds it to the form. That means you wouldn't even need an explicit button for the purpose. However, the one downside to this approach is that it's necessarily bound to the browser and machine the user is currently editing on (since it's client-side). If they moved to a different computer, they would not be able to resume their edits.

ASP.NET MVC multiple controller actions in one form

If the form submit does a POST (submit) to the comments page (i.e. has the action of the comments page, and the method of POST), then it is indeed the POST version that chouls be used. The GET version would be used if you (for example) use a standard anchor/link to show the standalone comments page (or when issuing an AJAX "get" to that address).

How are you currently hitting the pages? At the moment it sounds like your index page is adding the form manually - so there is no place for the comments GET to be used, unless you are adding the form via AJAX.

How to assign the same controller method to handle two forms on two different views?

I think you have add a parameter to distinguish the two views,suppose the parameter is called viewType, then you can do it as follow:

contact-us.html

<form action="#" th:action="@{/sendMailSimple}"
th:object="${mailForm}" role="form" id="contact-form"
method="post">
<input type="hidden" name="viewType" value="contact-us"/>
...
</form>

home.html

<form id="contact-form" method="post"
action="#" th:action="@{/sendMailSimple}"
th:object="${mailForm}" role="form">
<input type="hidden" name="viewType" value="home"/>
...
</form>

So in controller we can get the viewType parameter:

@RequestMapping(value = "/sendMailSimple", method = RequestMethod.POST)
public String sendSimpleMail(@Valid @ModelAttribute("mailForm") final Mail mailForm, String viewType,BindingResult bindingResult)
throws MessagingException {
mailValidator.validate(mailForm, bindingResult);

if (bindingResult.hasErrors()) {
return "contact-us";
}

mailForm.setRecipientEmail("contact-test@gmail.com");
this.emailServiceImpl.sendSimpleMail(mailForm);

if(viewType.equals("contact-us")){
return "contact-us"
}else{
return "home";
}
//return viewType;can also return the viewType directly

}


Related Topics



Leave a reply



Submit