Example, i made a form like this
<form name="register" method="post" enctype="multipart/form-data">
<p><h3>User check</h3></p>
<p>admin ID: <input type="text" name="userid"></p>
<p>admin Pass: <input type="password" name="password"></p>
<input type="submit" name="apply" value="Submit"></p>
<p> </p>
</form>
and my manager wants to change this form to rails form template like this,
<%= form_for(:model) do |form| %>
<p>
<%=form.label :input%>
<%=form.text_field :input, :placeholder => 'Enter text here...'%>
</p>
<%end%>
My question is, it works fine with html based front code. Why do i have to change this to rails code? I just want to keep my front-end code...I don't know why i have to change this :(. Also, I'm new on Ruby on Rails. That is the main reason. I dont' want to change the existing code, if it is working.
I really hate this job. I have to translate all the attributes to the rails code and that makes me really exhausted :(
Form builders are here to help
Form helpers are supposed to make your life simpler. They are quicker to write than their pure html alternative, provided you don't write pure html first.
They also provide a lot of easy implementations for difficult integration pieces, like :
displaying a date selection select group
mirroring the fact that a check box has been unchecked in POST params
automatically adding multipart param on form if you add a file input (not actually difficult to achieve, but easy to forget)
... and many more
Further development
All of this is about comfort, and you may think you could avoid it if you already have a perfectly working pure html implementation.
But what happen if someone later has to add a date select input in your form ? She will have to use the rails helper, since it saves a lot of time in controller part to set date in database. But she won't be able to leverage form builder, since you haven't used it.
Now, she has to choose between using a non builderdate_select tag mixed in pure html or ... to rewrite your form completely. As you may realize, mixing different styles is generally considered ugly, and we don't like ugly in ruby.
Security
Form tag helpers also provide an important security measure : CSRF protection. Every time you use a rails helper to create a <form> tag, it automatically adds an hidden input containing a secret key. That key has to be posted with form data to prove request originated from current website.
If you use plain html forms, you won't have this security. You could of course add the token manually using the correct method, but this would again be more time wasting than simply using form helpers.
Bottom line
The main problem is that you write pure html before using rails helpers - that is what is wasting time.
Some benefits of using Rails form helpers are:
Consistent naming of input elements names and ids
i18n support for labels
generated URL with form_for is less error prone
Better handling of checkboxes
Nice helpers like options_for_select
Less typing
That last ones might be my favourite: less typing.
Related
I've been working with Ruby & RoR for a few weeks now and must say, this is a beautiful language, it's been very enjoyable to work with.
I'm hoping someone can point me in the right direction for an article that explains collecting user inputs on the frontend, everything I've found so far has been confusing.
Basically, I want to create an input field in a front end view that passes the result to my controller so I can feed it to an API wrapper.
In irb I can do this, but I don't understand the equivalent for a view that's accessible on the front end.
customeremail = gets.chomp
ticketfind = Desk.customers(:email => customeremail)
I don't necessarily need to store the data in a database, I'd almost rather prefer not to. Basically just need the input to pass off to the API, so I can redirect to a form which I'll submit to the API. I'm certain I can figure it out with some good links, I just don't think I'm googling the right thing.
Thanks for reading!
What you want is a simple form on your view...
<%= form_tag "/my_controller/my_action" do %>
<%= text_field_tag ":customer_email" %>
<%= submit_tag "Save" %>
<% end %>
This site explains about form_tag
http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html
And in your my_controller your my_action method...
def my_action
ticketfind = Desk.customers(:email => params[:customer_email])
Unlike Josh I prefer to use form helpers, but there's always more than one way to do it.
When forms are submitted in HTML they create a POST request to the server based on the URL you pointed the form to. The server picks up the POST request and maps it to the controller via your route map.
Ex:
<!-- This will POST form data to localhost:3000/users/create -->
<form action='users/create'>
<input type='text'/>
<input type='submit'/>
</form>
This should ping your server and route to UsersController#create. Rails stashes the form data in params
http://www.w3schools.com/tags/att_form_action.asp
I would recommend that you learn to do this without ERB first. Create a form with raw HTML so you can start to learn what's going on. You can use an ERB template, but only embed the variables in Ruby (e.g. don't use form helpers). You can then refactor to that (I personally prefer raw HTML over ERB heleprs). If you use Chrome or FF, you can open up the developer console and watch how the network requests work when you submit the form (I forget if this clears with each refresh or not, so you might not actually be able to do this in this example, but it's helpful in AJAX flows)
Form builder behaves unexpectedly when building a form within a table. It closes the form immediately.
Yes, I know that tables are generally bad. But in this case, I'm displaying line items for billing purposes, which is a pretty good use case for tables.
Each row is designed to be its own form that auto-submits on change.
View Source
I'm not sure if this is by design in Rails, or if it's a bug.
I get the whole opinionated software thing, but this behavior is a little extreme.
I promise that there are no bombs in my shoes. The framework should let me do what I want, even if you think it's stupid.
At this point I'm ready to copypasta the raw HTML myself. But, I really shouldn't have to.
What do you guys think (if that's not too gender normative)?
Your tool is acting correctly in this case, you are asking it to create a form under a tr.. when you should encase it in a th like you have for the Service, notes, and cost..
in short you can not have a "<%= form_for" directly under a tr.. move it into a th
I think the HTML generated by Rails would be the one you expect, it is the browser which parses the HTML which is having trouble with it. You can check that by using View Page Source instead of using Inspect Element to view the HTML generated.
My guess is the HTML from the view source would be something along the lines of:
<form class="submitless" action="/tickets/1294/labors/1090" method="post">
<td class="service">
<select>...</select>
...
</td>
</form>
But since this is not valid HTML, the browser might be having a hard time understanding it and is parsing it wrongly.
What is a good approach in ASP.NET MVC for implementing a complex form where sections of the form are shown and hidden based on a user's inputs?
My background is in Webforms. I am frequently asked to build forms where a user selects an option from a dropdown list, triggering a handful of new fields to appear. A different selection might cause a different set of fields to appear.
In the past, I would handle this scenario via an UpdatePanel and a wrapper Panel around the fields that I want to show or hide. Validation is automatically disabled when the fields are hidden.
Going forward, I'd like to make use of MVC's attribute-based model validation, but is it possible to make the validation conditional on the values of other properties?
Also, how can I handle the toggling of blocks of form fields? I know how to do it manually in jQuery, but I'm hoping there's an approach that ties in with validation and server-side code.
I am liking MVC much better overall, but I haven't figured out how to handle this type of scenario very well. Likely I just need to shift my thinking to fit better with the MVC approach.
Josh,
The first thing I's suggest is to make sure you use ViewModels for the pages that are mode complicated. A ViewModel is basically a Model you create for a specific View; for example, a ViewModel could be a composition of other classes.
As for dynamically changing the fields on your View, the best way is to use jQuery (or any other javascript library) to do it.
I also migrated from a web form environment and I know is difficult to change gears at the begining, but trust me, doing a simple jQuery even handler is much simpler than having to put in place a control panel and then the event handlers.
Not to mention that is much more efficient; update panels are after all making partial posts to the page, sometimes, with jQuery you don't even need to do that.
After a few projects with MVC, I actually now find it time consuming to go and do the Update Panels on web forms ;)
Hope this helps,
-Covo
I know this might not be the answer you're looking for, but I personally don't think complex forms are very user friendly in the first place and I always try to split them up into simpler forms where possible, or to simplify the form. I've come across many forms in websites where there are a raft of "fields" where there should really be a few questions for the user to answer. Simple stuff which gets to the point of what they want to achieve rather than the field values, along with a lot of application specific knowledge needed to set those fields to the right values.
If you still want to go ahead with a complex form, then as the other answers have already stated there are facilities provided by MVC to do that, but there isn't any set way. So, it's down to you to figure out what will work best for your users.
Traditional asp.net webforms did alot of "magic" for you whereas you have to be aware of the work that goes into creating the "magic" in asp.net MVC. The benefit is that with MVC you have more control over what is happening which can also enhance performance.
In asp.net webforms an UpdatePanel is used for ajax calls. If you need to got to the server asynchronously(without doing a full post back) then use ajax via JQuery. See below for example:
$.ajax({
type: "get",
url: "/YourController/YourAction",
success: function (obj) {
//any logic you want to do upon success
}
});
The above example will do an ajax HTTP GET call to /YourController/YourAction.
In order to handle "toggling of blocks", if you don't need to go to the server for data and you simply want to do it on the client, then use simple jquery. JQuery has a function for toggling items.
http://api.jquery.com/toggle-event/
Because of the way MVC works in contrast to Webforms you're stuck with the responsibility of really thinking about what happens on the client and what happens on the server separately as not a lot of meta-data is being passed back to give us that happy Webforms feeling.
However, there is a notion when using the built-in AJAX libraries when you render a form that you can have it auto do an update once it is posted. In a sense, it's saving you the JavaScript/JQuery because it "auto-wires" it up similar-ish to a Panel. In this way you could potentially look at progressively rendering your complex forms from the server as each section is edited, etc.
See MSDN: http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxoptions.updatetargetid.aspx
The relevant code example to give you an idea (unfortunately, it's not in the more readable Razor syntax):
The relevant line is the Ajax.BeginForm where the form tag is rendered. Once the form is posted, the MS AJAX library will auto update the element specified in "UpdateTargetId" specified in the form's AjaxOptions. In this case, the response will be placed into the SPAN element "textEntered" upon reply from the server. Here, you could progressively render more content to the user to fill out, perhaps another form, etc.
<h2><%= Html.Encode(ViewData["Message"]) %></h2>
<p>
Page Rendered: <%= DateTime.Now.ToLongTimeString() %>
</p>
<span id="status">No Status</span>
<br />
<%= Ajax.ActionLink("Update Status", "GetStatus", new AjaxOptions{UpdateTargetId="status" }) %>
<br /><br />
<% using(Ajax.BeginForm("UpdateForm", new AjaxOptions{UpdateTargetId="textEntered"})) { %>
<%= Html.TextBox("textBox1","Enter text")%>
<input type="submit" value="Submit"/><br />
<span id="textEntered">Nothing Entered</span>
<% } %>
It seems like everything I look up on this subject has either changed since the release or is wildly different from eachother.
I just want to create a simple form in my view.
Should I be using the Html.BeginForm()/TextBox()/EndForm() methods or should I be using a plain-jane HTML form? Which is preferred?
This is what I have so far:
<%=Html.BeginForm("Create", "Product", FormMethod.Post); %>
<%=Html.TextBox("productTextBox", "Enter a shoe name"); %>
<input type="submit" name="createButton" value="Create Me!" />
<%=Html.EndForm(); %>
What is the "correct" way to create a simple form with a button and textbox in ASP.NET MVC and allow me to submit the data in the form to the /Product/Create action?
How do I then access the form data from within that method? Some people seem to use a "FormCollection" and others just do a Request.Form method. Which way should I use?
Can someone enlighten me?
The Form helpers are the recommended way because it allows you to provide a controller, action and other route data and the URL is auto-generated based on your routes (in Global.asax). The advantage is, if you decide to change your routes, you don't have to update every URL in your site.
The only reason I'd use an actual "<form>" tag was if I needed extra control over the markup that I couldn't get from Html.Form (I can't think of an example right now). Even if you choose to do that, you should use the "Url.Action" helper to get a URL from routing data. For example:
<form action="<%= Url.Action("Create") %>">
As for your second question, I'd suggest using the Model Binder. Check out ScottGu's Blog for some details on this.
Have a look at Link.
It's German text but the code should be understandable.
Have you looked at this:
http://weblogs.asp.net/scottgu/archive/2009/03/10/free-asp-net-mvc-ebook-tutorial.aspx
It's from the horse's mouth, and is up-to-date with the final release.
Is there a specific reason why I should be using the Html.CheckBox, Html.TextBox, etc methods instead of just manually writing the HTML?
<%= Html.TextBox("uri") %>
renders the following HTML
<input type="text" value="" name="uri" id="uri"/>
It guess it saves you a few key strokes but other than that. Is there a specific reason why I should go out of my way to use the HtmlHelpers whenever possible or is it just a preference thing?
Another benefit is that if your ViewData contains a value matching the name of the field it will be populated.
e.g.
ViewData["FirstName"] = "Joe Bloggs";
<%=Html.TextBox("FirstName") %>
will render
<input type="text" value="Joe Bloggs" id="FirstName" />
There are huge benefits:
It has overloaded methods to pre-populate the values (formatted, and safe for HTML) just like the ViewState.
It allows built in support for the Validation features of MVC.
It allows you to override the rendering by providing your own DLL for changing the rendering (a sort of "Controller Adapter" type methodology).
It leads to the idea of building your own "controls" : http://www.singingeels.com/Articles/Building_Custom_ASPNET_MVC_Controls.aspx
One thing is for consistency...I for one always forget the name attribute. Plus, you can extend the functions for your own projects. They're not called helpers for nothing!
The upside to using an abstraction layer is future proofing your code in a pluggable way. Maybe today, you create HTML 4 pages but tomorrow you want to create XHTML pages or XAML or XUL. That's a lot of changes if you just hard code the tags everywhere, especially if you've got hundreds of pages. If everything is calling this library, then all you've got to do is rewrite the library. The downside is that it is usually considered to be slightly less readable by humans. So, it most probably increases the cognitive demand on your maintenance programmers. These advantages and disadvantages really have nothing to do with MVC.
It actually auto populates your textbox based upon first your ViewData.Model.uri and second by ViewData["uri"]. Doing it manually you'd need to do <input value="<%Html.Encode(ViewData.Model.Uri"%>" />
I haven't been doing MVC too long, but I've already written some extension methods to generate menu tabs based on Html.ActionLink. It allows me to be consistent with my usage and, if I decide to change how my CSS menus work, only modify a single method to output the new tab format.
The other use that I have made of them is in conditional output using ViewData to supply values to the controls.