1 / 7

Simple Form

Simple Form. <form action="/x/y/z" method="POST"> Value1: <input type="text" name="value1"/><br /> Value2: <input type="text" name="value2" value="47"/> <input type="submit" value="Submit"/> </form>. Rails Form Helpers. Name of model class (Student). Name of variable containing

Download Presentation

Simple Form

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Simple Form <form action="/x/y/z" method="POST"> Value1: <input type="text" name="value1"/><br /> Value2: <input type="text" name="value2" value="47"/> <input type="submit" value="Submit"/> </form> CS 142 Lecture Notes: Forms

  2. Rails Form Helpers Name of modelclass (Student) Name of variable containing data (@student) <% form_for(:student, :url => {:action => :modify, :id =>@student.id}) do |form| %> <table class="form"> <tr> <td class="label">Name:<td> <td><%=form.text_field(:name)%><td> </tr> <tr> <td class="label">Date of birth:<td> <td><%= form.text_field(:birth) %><td> </tr> ... <table> <%= submit_tag "Modify Student" %> <% end %> Initial value will be@student.name Text to displayin submit button <input id="student_name" name="student[name]" size="30" type="text" value="Hernandez" /> CS 142 Lecture Notes: Forms

  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 CS 142 Lecture Notes: Forms

  4. Validation Custom validation method class Student < ActiveRecord::Base def validate if (gpa < 0) || (gpa > 4.0) then errors.add(:gpa, "must be between 0.0 and 4.0") end end validates_format_of :birth, :with => /\d\d\d\d-\d\d-\d\d/, :message => "must have format YYYY-MM-DD“ end Built-in validator Saves error info CS 142 Lecture Notes: Forms

  5. Error Message Helper <%= error_messages_for(:student)%> <% form_for(:student, :url => {:action => :modify, :id =>@student.id}) do |form| %> ... <%= form.text_field(:name) %> ... <% end %> CS 142 Lecture Notes: Forms

  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

  7. CS 142 Lecture Notes: Forms

More Related