CSC/ECE 517 Fall 2012/ch1b 1w66 as: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(44 intermediate revisions by 2 users not shown)
Line 6: Line 6:
example, Text box can fetch a few words from the user and Text Area, a paragraph. Forms are embedded in a Web Application and are very user-friendly.
example, Text box can fetch a few words from the user and Text Area, a paragraph. Forms are embedded in a Web Application and are very user-friendly.
Forms in Rails also have in-built functionalities to verify the data the user enters, validate it using a set of predefined rules, display corresponding error messages(in case of non-compliance) and storing the information in the database if it passes validation.
Forms in Rails also have in-built functionalities to verify the data the user enters, validate it using a set of predefined rules, display corresponding error messages(in case of non-compliance) and storing the information in the database if it passes validation.
<br>
<br/>
<br>
<br/>
 
==Creating a Form==
==Creating a Form==
Forms written in Rails are automatically generated into HTML Forms and are rendered into views.
Forms written in Rails are automatically generated as HTML Forms and are rendered into views.
Forms are created in Rails using the basic helper called Form_tag
Forms are created in Rails using the basic helper called Form_tag
<pre>
<pre>
Line 16: Line 17:
<% end %>
<% end %>
</pre>
</pre>
When form_tag is called as above, it creates a <form> tag which, when submitted, will POST to the current page. For instance, assuming the current page is /home/index, the generated HTML will look like this (some line breaks added for readability): [http://edgeguides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease]
When form_tag is called as above, it creates a <form> tag which, when submitted, will POST to the current page. For instance, assuming the current page is /home/index, the generated HTML will look like this (some line breaks added for readability): <ref>http://edgeguides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease</ref>
<pre>
<pre>
<form accept-charset="UTF-8" action="/home/index" method="post">
<form accept-charset="UTF-8" action="/home/index" method="post">
Line 28: Line 29:
Forms in Rails consist of Elements, which are labels, input elements, submit buttons etc.
Forms in Rails consist of Elements, which are labels, input elements, submit buttons etc.
<br/><br/>
<br/><br/>
===Example of the Call Super Anti-pattern===
===Text Fields===
In the example below, the super class of TestCase is extended by the TestCaseOne classThe subclass TestCaseOne calls setup at the beginning of its own setup() method and then does any extra steps.
Text Fields in Rails Forms allow the user to input a few words or a single word. These are generally used to capture Names, Addresses, Phone numbers etc. To create a text field in Rails Forms use the following syntax:<ref>http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm</ref>
<pre>
<%= text_field :modelname, :attribute_name, options %>
</pre>
In the example below we create a text field of size 20 characters :
<pre><%= text_field "person", "name", "size" => 20 %></pre>
This will generate following code:
<pre>
<input type="text" id="person_name" name="person[name]"
      size="20" value="<%= @person.name %>" />
</pre>
Rails also allows us to create Hidden Fields. Hidden Fields don't show up on the Page and hence can contain any value which the user cannot see or change. To create hidden fields use the following syntax;
<pre>
<%= hidden_field ... %>
</pre>
To create password fields use the following syntax;
<pre>
<%= password_field ... %>
</pre>
To create file upload fields use the following syntax;
<pre>
<%= file_field ... %>
</pre>
===TextArea Fields===
Text Area Fields allow us to enter information in paragraphs, i.e, enter data that has more than a few words and sentences. Text Area Fields are also adjustable in size. To change the size of a Text Area Field, we are required to change the rows and cols values to numbers of our interest. <ref>http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm</ref>
To create a text area use the following syntax:
<pre>
<%= text_area ... %></pre>
Example:
<pre>
<%= text_area "post", "body", "cols" => 20, "rows" => 40%></pre>
This will generate the following code:
<pre>
<textarea cols="20" rows="40" id="post_body" name="post[body]">
<%={@post.body}%>
</textarea>
</pre>
===Radio Button===
Rails Forms can also include Radio Button, for choice based User Inputs. To create a radio button, use the following Syntax <ref>http://apidock.com/rails/ActionView/Helpers/FormHelper/radio_button</ref>:
<pre><%= radio_button :modelname, :attribute, :tag_value, options %></pre>
Consider example:
<pre>
  radio_button("post", "category", "rails")
radio_button("post", "category", "java")
</pre>
This will generate following code:
<pre>
<input type="radio" id="post_category" name="post[category]"
value="rails" checked="checked" />
<input type="radio" id="post_category" name="post[category]"
                    value="java"= /></pre>
 
===Checkbox Button===
Checkboxes can be added to Forms in Rails, using the following syntax<ref>http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm</ref>
<pre><%= check_box :modelname, :attribute,options,on_value,off_value%></pre>
Consider the following example:
<pre>check_box("post", "validated")</pre>
This generate following code:
<pre>
<pre>
public class TestCase{
<input type="checkbox" id="post_validate" name="post[validated]"
  public void setup() {
                                  value="1" checked="checked" />
    ...
<input name="post[validated]" type="hidden" value="0" />
  }
}
public class TestCaseOne extends TestCase{
  public void setup() {
    super.setup();
    ...
  }
}
</pre>
</pre>
===Dropdown List===
Dropdown Lists in Forms allow users to select a value from a set of predefined values. <ref>http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm</ref>To create a drop-down list use the following syntax:
<pre>
<%= select :variable,:attribute,choices,options,html_options%</pre>
Have a look at the following example:
<pre>
select("post", "person_id",
      Person.find(:all).collect {|p| [ p.name, p.id ] })
This could generate following code. It depends on what value is available in your database.:
  <select name="post[person_id]">
    <option value="1">David</option>
    <option value="2">Sam</option>
    <option value="3">Tobias</option>
  </select>
</pre>
=== The Submit Button===
Submit button in Rails will perform the desired action the form is linked to, and is usually located in the bottom, where the form ends. Submit button sends the data in the form through POST/GET actions in HTML.
<br/>
==Actions==
The action attribute in Rails Forms specifies what to do when a Form is submitted<ref>http://paulsturgess.co.uk/articles/49-using-helper-methods-in-ruby-on-rails</ref>. The action attribute is specified in form_tag itself. For example, 
<pre>
  <%= form_tag :action => "create" %>
  Name: <%= text_field "item", "name"
%><br />
  Value: <%= text_field "item", "value"
%><br />
  <%= submit_tag %>
  <%= end_form_tag %>
</pre>
For the object "item"  in the example above, the Controller ItemsController should include a method called "create" which will respond to the form's action. We add the method "Create" in the code below:
<pre>
class ItemsController < ApplicationController
    def new
      @item = Item.new
    end
#add method create
    def create
      @item = Item.create(params[:item])
      redirect_to :action => 'edit', :id => @item.id
    end
#add method create
  end</pre>
If more actions are desired, corresponding methods must be added in the Controller class of the object.
==Routes==
In rails,routes are used to automatically direct a HTTP request to the appropriate controller action.
With the help of routes one can easily name and configure a URL path i.e the routing engine can figure out where to go and which action to invoke for a given URL. This also works in reverse, which in turn reduces the rigidness in your application structure. <ref>http://guides.rubyonrails.org/v2.3.11/routing.html#crud-verbs-and-actions</ref>
==Views==
Views are used to render forms or data to the user. It displays only necessary information and hides internal workings from the user.
In views it is more about presentation of data than the data itself. More focus is given to layout and template so as to make it easily readable for the end user.
===Views in forms===
In Rails, each form element has a name which controls how values will appear in the controller which has the params hash.
When we use params rails automatically does the required HTTP parsing  for populating the instance.
Also one of the main advantages of ruby is that it has many features which can be used to reduce repetition of code for generating views.
One was the ways this can be done is to use helper modules which by default have excellent ruby support.


==Alternative Implementation==
==Helpers==
Instead of forcing a method to call super(), it is generally considered a better practice to use the [http://en.wikipedia.org/wiki/Template_method_pattern template method pattern.]  In this pattern, the method that would be required to be called via super(), that method would actually call another method that is abstract has to be created by the subclass.
Can be used to define any piece of code which will be called many times by the view. Helper methods mainly are used to provide functionality in the views. Also default helper programs can used for otherwise cumbersome to implement functions like date etc<ref>http://www.railsforum.com/viewtopic.php?id=1026</ref>
 
===Helpers in forms===
Helpers are used to hide view logic form the end user. Ideally all business logic need to be present in model methods but if one needs to add logic in the view itself then writing the helper method is a good design choice.<br/>
Inbuilt options in rails:
We have many default helper methods in rails which provide us with ready to use option for most commonly used things in a form.
Some example for default helpers are:<br/>
• Linking and form building<br/>
• Date and Time methods
 
 
==Things to do with forms==
 
1) Generate/display – This relates to presenting a layout by using templates to the user.<br/>
2) Values filling by user -
Take input from the user for the generated form by providing buttons,text boxes or drop downs.<br/>
3) Render after form creation-
After the form is filled and ready, the form should get submitted and the required data must be saved.<br/>
 
==General steps to create forms==
• Identify action that fetches the form <br/>
• Identify actions that handle form submission<br/>
• Create routes, action, views for each<br/>
 
==What does a form look like?==
Below is a sample form which can be used to add a new entry. A entry has a topic with some content and a checkbox option as a functionality. Notice the use of the format modelname.field as this is the convention genrerally followed. This helps in easy understandably of code later on.


===Example Using Alternative Implementation (Template Method Pattern)===
In the example below, the super class implementation of setup() calls another method doExtraStuff() which is abstract and therefore has to be implemented by the subclass when it is extended.
<pre>
<pre>
public class TestCase{
<h1>Add a new entry</h1>
  public void setup() {
    .....
    doExtraStuff();
  }
  abstract void doExtraStuff();
}


public class TestCaseOne extends TestCase{
<%= form_for  @entry do |f|  %>
  void doExtraStuff() {
    <p>
     ...
      <%= f.label :topic  %> <br />
  }
      <%= f.text_field :topic  %>
}
     </p>
    <p>
      <%= f.label :content  %><br />
      <%= f.text_area :content %>
    </p>
<p>
      <%= f.label :tick %><br />
      <%= f.check_box :tick %>
</p>
    <p>
      <%= f.submit "Add a new Entry" %>
    </p>
<% end %>
</pre>
</pre>
==Conclusion==
Forms in Rails are a great way to interact and obtain data from the user. Additionally, forms also support validation checks.
Other major advantages of forms are that they are easy to maintain and readable not only from the users viewpoint but also for the developers. 


==References==
==References==
<references></references>
<references></references>
==See Also==
[http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm Rails Forms]<br/>
[http://www.devarticles.com/c/a/Ruby-on-Rails/Web-Forms-and-Ruby-on-Rails Web forms in Rails]<br/>
[http://rubypond.com/blog/sexy-forms-in-rails Rails Form Designs]<br/>
[http://ruby.about.com/od/mechanize20handbook/a/Forms-In-Mechanize_4.htm Forms in Rails in Mechanize]<br/>
[http://pragprog.com/screencasts/v-rbforms/mastering-rails-forms Rails Forms in Rails - Mastering Rails Forms]<br/>
[http://www.buildingwebapps.com/transcript/79330-rails-form-processing Rails Forms Processing]<br/>
[http://paulsturgess.co.uk/articles/49-using-helper-methods-in-ruby-on-rails Rails Helper Methods]<br/>

Latest revision as of 06:37, 10 October 2012

Forms-Ruby

Introduction

Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup.<ref>http://www.guides.rubyonrails.org/form_helpers.html</ref> Rails provides excellent features to create forms and gather user input. Forms in Rails are an effective way to obtain user input in a convenient manner. Forms can include different types of data fields that will help obtain different types of data. For example, Text box can fetch a few words from the user and Text Area, a paragraph. Forms are embedded in a Web Application and are very user-friendly. Forms in Rails also have in-built functionalities to verify the data the user enters, validate it using a set of predefined rules, display corresponding error messages(in case of non-compliance) and storing the information in the database if it passes validation.

Creating a Form

Forms written in Rails are automatically generated as HTML Forms and are rendered into views. Forms are created in Rails using the basic helper called Form_tag

<%= form_tag do %>
  Form contents
<% end %>

When form_tag is called as above, it creates a <form> tag which, when submitted, will POST to the current page. For instance, assuming the current page is /home/index, the generated HTML will look like this (some line breaks added for readability): <ref>http://edgeguides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease</ref>

<form accept-charset="UTF-8" action="/home/index" method="post">
  <div style="margin:0;padding:0">
    <input name="utf8" type="hidden" value="✓" />
    <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
  </div>
  Form contents
</form>

Forms in Rails consist of Elements, which are labels, input elements, submit buttons etc.

Text Fields

Text Fields in Rails Forms allow the user to input a few words or a single word. These are generally used to capture Names, Addresses, Phone numbers etc. To create a text field in Rails Forms use the following syntax:<ref>http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm</ref>

<%= text_field :modelname, :attribute_name, options %>

In the example below we create a text field of size 20 characters :

<%= text_field "person", "name", "size" => 20 %>

This will generate following code:

<input type="text" id="person_name" name="person[name]"
      size="20" value="<%= @person.name %>" />

Rails also allows us to create Hidden Fields. Hidden Fields don't show up on the Page and hence can contain any value which the user cannot see or change. To create hidden fields use the following syntax;

<%= hidden_field ... %>

To create password fields use the following syntax;

<%= password_field ... %>

To create file upload fields use the following syntax;

<%= file_field ... %>

TextArea Fields

Text Area Fields allow us to enter information in paragraphs, i.e, enter data that has more than a few words and sentences. Text Area Fields are also adjustable in size. To change the size of a Text Area Field, we are required to change the rows and cols values to numbers of our interest. <ref>http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm</ref> To create a text area use the following syntax:

<%= text_area ... %>

Example:

<%= text_area "post", "body", "cols" => 20, "rows" => 40%>

This will generate the following code:

<textarea cols="20" rows="40" id="post_body" name="post[body]">
<%={@post.body}%>
</textarea>

Radio Button

Rails Forms can also include Radio Button, for choice based User Inputs. To create a radio button, use the following Syntax <ref>http://apidock.com/rails/ActionView/Helpers/FormHelper/radio_button</ref>:

<%= radio_button :modelname, :attribute, :tag_value, options %>

Consider example:

 radio_button("post", "category", "rails")
 radio_button("post", "category", "java")

This will generate following code:

<input type="radio" id="post_category" name="post[category]" 
value="rails" checked="checked" />
<input type="radio" id="post_category" name="post[category]" 
                    value="java"= />

Checkbox Button

Checkboxes can be added to Forms in Rails, using the following syntax<ref>http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm</ref>

<%= check_box :modelname, :attribute,options,on_value,off_value%>

Consider the following example:

check_box("post", "validated")

This generate following code:

<input type="checkbox" id="post_validate" name="post[validated]" 
                                   value="1" checked="checked" />
<input name="post[validated]" type="hidden" value="0" />

Dropdown List

Dropdown Lists in Forms allow users to select a value from a set of predefined values. <ref>http://www.tutorialspoint.com/ruby-on-rails/rails-html-forms.htm</ref>To create a drop-down list use the following syntax:

<%= select :variable,:attribute,choices,options,html_options%

Have a look at the following example:

select("post", "person_id", 
       Person.find(:all).collect {|p| [ p.name, p.id ] })
This could generate following code. It depends on what value is available in your database.:
  <select name="post[person_id]">
    <option value="1">David</option>
    <option value="2">Sam</option>
    <option value="3">Tobias</option>
  </select>

The Submit Button

Submit button in Rails will perform the desired action the form is linked to, and is usually located in the bottom, where the form ends. Submit button sends the data in the form through POST/GET actions in HTML.

Actions

The action attribute in Rails Forms specifies what to do when a Form is submitted<ref>http://paulsturgess.co.uk/articles/49-using-helper-methods-in-ruby-on-rails</ref>. The action attribute is specified in form_tag itself. For example,

  <%= form_tag :action => "create" %>
   Name: <%= text_field "item", "name"
%><br />
   Value: <%= text_field "item", "value"
%><br />
   <%= submit_tag %>
  <%= end_form_tag %>

For the object "item" in the example above, the Controller ItemsController should include a method called "create" which will respond to the form's action. We add the method "Create" in the code below:

class ItemsController < ApplicationController
    def new
      @item = Item.new
    end
#add method create
    def create
      @item = Item.create(params[:item]) 
      redirect_to :action => 'edit', :id => @item.id 
    end
#add method create
  end

If more actions are desired, corresponding methods must be added in the Controller class of the object.

Routes

In rails,routes are used to automatically direct a HTTP request to the appropriate controller action. With the help of routes one can easily name and configure a URL path i.e the routing engine can figure out where to go and which action to invoke for a given URL. This also works in reverse, which in turn reduces the rigidness in your application structure. <ref>http://guides.rubyonrails.org/v2.3.11/routing.html#crud-verbs-and-actions</ref>

Views

Views are used to render forms or data to the user. It displays only necessary information and hides internal workings from the user. In views it is more about presentation of data than the data itself. More focus is given to layout and template so as to make it easily readable for the end user.

Views in forms

In Rails, each form element has a name which controls how values will appear in the controller which has the params hash. When we use params rails automatically does the required HTTP parsing for populating the instance. Also one of the main advantages of ruby is that it has many features which can be used to reduce repetition of code for generating views. One was the ways this can be done is to use helper modules which by default have excellent ruby support.

Helpers

Can be used to define any piece of code which will be called many times by the view. Helper methods mainly are used to provide functionality in the views. Also default helper programs can used for otherwise cumbersome to implement functions like date etc<ref>http://www.railsforum.com/viewtopic.php?id=1026</ref>

Helpers in forms

Helpers are used to hide view logic form the end user. Ideally all business logic need to be present in model methods but if one needs to add logic in the view itself then writing the helper method is a good design choice.
Inbuilt options in rails: We have many default helper methods in rails which provide us with ready to use option for most commonly used things in a form. Some example for default helpers are:
• Linking and form building
• Date and Time methods


Things to do with forms

1) Generate/display – This relates to presenting a layout by using templates to the user.
2) Values filling by user - Take input from the user for the generated form by providing buttons,text boxes or drop downs.
3) Render after form creation- After the form is filled and ready, the form should get submitted and the required data must be saved.

General steps to create forms

• Identify action that fetches the form
• Identify actions that handle form submission
• Create routes, action, views for each

What does a form look like?

Below is a sample form which can be used to add a new entry. A entry has a topic with some content and a checkbox option as a functionality. Notice the use of the format modelname.field as this is the convention genrerally followed. This helps in easy understandably of code later on.

<h1>Add a new entry</h1>

<%= form_for  @entry do |f|  %>
    <p>
      <%= f.label :topic  %> <br />
      <%= f.text_field :topic  %>
    </p>
    <p>
      <%= f.label :content  %><br />
      <%= f.text_area :content %>
    </p>
<p>
      <%= f.label :tick %><br />
      <%= f.check_box :tick %>
</p>
    <p>
      <%= f.submit "Add a new Entry" %>
    </p>
<% end %>

Conclusion

Forms in Rails are a great way to interact and obtain data from the user. Additionally, forms also support validation checks. Other major advantages of forms are that they are easy to maintain and readable not only from the users viewpoint but also for the developers.

References

<references></references>

See Also

Rails Forms
Web forms in Rails
Rails Form Designs
Forms in Rails in Mechanize
Rails Forms in Rails - Mastering Rails Forms
Rails Forms Processing
Rails Helper Methods