rss
twitter
    Find out what I'm doing, Follow Me :)

Observe_form for getting Live preview

You’d like to give your users the ability to see a live preview of their data
as they are editing it. You don’t want them to have to wait until they
submit a form. So that if there is any error it can be rectified.

Include the javascripts in the layouts.

<%= javascript_include_tag "default" %>

Now that we’ve got the necessary JavaScript libraries loaded, we’ll create
the model and controller.Suppose the controller name is Content and model name is Example. There are two fields in the table ('title' and 'body' )

Now in the model define the attribute accessor

class Example
attr_accessor :title, :body
end


We will create a new method

def new
@data= Example.new
end



Create the file, app/views/content/new.rhtml, and edit it to look like
the following.

<% form_for(:example,:url => {:action=>'create',:html => {:class=>'wufoo', :id => "form"} ) do |form| %>
<%= text_field :example, :title %>

<%= text_area :example, :body %>

<%= submit_tag "Save" %>
<% end %>
<%= observe_form "form",
:frequency => 5,
:update => "preview",
:complete => "Element.show(' preview' )",
:url => { :action => "preview" } %>


In the method preview we write

def preview
render :layout => false
end



The only job of the action code is to short circuit the application’s usual
rendering. Since we’re going to be updating the live-preview element of
our diary entry creation page with the full results of the preview( ) action,
we don’t want it returning a full HTML page.

The preview action’s view, in app/views/content/preview.rhtml should look
like this:

Form Preview


<%= params[:example][:title] %>


<%= textilize params[:example][:body] %>


That’s all there is to it! This view prints the entry’s title as an HTML
heading and then generates HTML output via the textilize( ) method. This
method uses the RedCloth library internally to transform very simple
text markup to HTML.

0 comments: