Writing an interactive form (Part 4)
I’m really considering shooting screencasts, blogging is tedious. I could talk stupid things and upload. How’d you like that?
Ok, last week we had a working app with a list widget showing the items. Today we’re gonna write a form widget to add new items. The code for this lesson is at tag 0.7.
1First thing to do is generating stubs.
$ script/generate widget item_form display create --haml create app/cells/item_form create app/cells/item_form.rb create app/cells/item_form/display.html.haml create app/cells/item_form/create.html.haml
The app/cells/item_form.rb file looks like this, after some editing.
1 2 3 4 5 6 | class ItemForm < Apotomo::StatefulWidget def display @todo = Todo.new render end end |
I create a new Todo so I can use it in the view.
2The view needs to be implemented, too!
app/cells/item_form/display.html.haml
1 2 3 4 5 6 7 | %h3 Create new item = error_messages_for :todo - form_to_event(:submit) do = text_area :todo, :text, :rows => 2 = submit_tag "Create Todo!" |
Easy. The only interesting here is the call to #form_to_event
which basically triggers a :submit event when the form is, nah, submitted (line 5).
3
Let’s append the form widget to our widget tree in app/controllers/dashboard_controller.rb.
1 2 3 4 5 6 7 8 9 10 | class DashboardController < ApplicationController include Apotomo::ControllerMethods def index use_widgets do |root| root << widget(:item_list, 'dashboard_list') root << widget(:item_form, 'new_item') end end end |
I call the widget new_item (line 7).
4Pluggin’ the widget into the controller again happens in app/views/dashboard/index.html.erb (line 10 and 12).
<h2>Dashboard</h2> <div class="slot"> <%= render_widget 'dashboard_list' %> </div> <div class="slot"> <%= render_widget 'new_item' %> </div>
5In order to process the form, we need to observe that :submit event, so I will extend the widget class a bit.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class ItemForm < Apotomo::StatefulWidget def display respond_to_event :submit, :with => :create @todo = Todo.new render end def create @todo.update_attributes(param(:todo)) render :view => :display end end |
The event handler (line 3) will execute the #create method when the form is submitted.
Nothing unusual happens there, I update the @todo and instruct the widget to render the former view display.html.haml.
6Entering some text into the form and pressing Submit yields the expected result! The new item gets saved.
However, the list doesn’t update so we can not see what we did. We should implement some notification so the list updates when there was a new item created.
That’s what we’re gonna do in the next lesson, the 12 minutes are over!

October 17th, 2010 at 4:21 am
Yeah! Screencasts rock. Easier for you to make and less brain power for us since we don’t need to imagine it.