Simple Form Product: Price: CS 142 Lecture Notes: Forms Slide 1 Rails Form Helpers Describes type, provides initial values {:action => :modify, :id =>

Download Report

Transcript Simple Form Product: Price: CS 142 Lecture Notes: Forms Slide 1 Rails Form Helpers Describes type, provides initial values {:action => :modify, :id =>

Simple Form
<form action="/product/update" method="post">
Product: <input type="text" name="product"/><br />
Price: <input type="text" name="price" value="49.95"/><br />
<input type="submit" value="Submit"/>
</form>
CS 142 Lecture Notes: Forms
Slide 1
Rails Form Helpers
Describes type, provides initial values
<%= form_for(@student, :url => {:action => :modify,
:id => @student.id}) do |form| %>
<%= form.text_field(:name) %>
Object representing
<%= form.text_field(:birth) %>
form
<%= form.submit "Modify Student" %>
<% end %>
<form action="/student/modify/4" method="post">
<input id="student_name" name="student[name]“
size="30" type="text" value="Chen" />
<input id="student_birth" name="student[birth]“
size="30" type="text" value="1990-02-04" />
<input name="commit" type="submit“
value="Modify Student" />
</form>
CS 142 Lecture Notes: Forms
Slide 2
Customize Format
<%= form_for(@student, :url => {:action => :modify,
:id =>@student.id}) do |form| %>
<table class="form">
<tr>
<td><%= form.label(:name, "Name:")%></td>
<td><%= form.text_field(:name) %></td>
</tr>
<tr>
<td><%= form.label(:birth, "Date of birth:")%></td>
<td><%= form.text_field(:birth) %></td>
</tr>
...
<table>
<%= form.submit "Modify Student" %>
<% end %>
CS 142 Lecture Notes: Forms
Slide 3
Post Action Method
Hash with all of form data
def modify
@student = Student.find(params[:id])
if @student.update_attributes(params[:student]) then
redirect_to(:action => :show)
else
render(:action => :edit)
end
end
Redirects on success
Redisplay form on error
CS 142 Lecture Notes: Forms
Slide 4
Validation (in Model)
Built-in validator
class Student < ActiveRecord::Base
validates_format_of :birth,
:with => /\d\d\d\d-\d\d-\d\d/,
:message => "must have format YYYY-MM-DD"
Custom validation method
def validate_gpa
if (gpa < 0) || (gpa > 4.0) then
errors.add(:gpa, "must be between 0.0 and 4.0")
end
end
Saves error info
validate :validate_gpa
end
CS 142 Lecture Notes: Forms
Slide 5
Error Messages
<% @student.errors.full_messages.each do |msg| %>
<p><%= msg %></p>
<% end %>
form_for(@student, :url => {:action => :modify,
:id =>@student.id}) do |form| %>
...
<%= form.label(:birth, "Date of birth:")%>
<%= form.text_field(:birth) %>
...
<% end %>
CS 142 Lecture Notes: Forms
Slide 6
File Uploads with Rails
<% form_for(:student, :html=>{:multipart => true}
:url => {...}) do |form| %>
...
<%= form.file_field(:photo) %>
...
<% end %>
In form post method:
params[:student][:photo].read()
params[:student][:photo].original_filename
CS 142 Lecture Notes: Forms
Slide 7
CS 142 Lecture Notes: Cookies
Slide 8