Badminton on Rails
RSS icon Home icon
  • Using Textile Editor Helper (TEH) in an Ajax environment

    Posted on July 10th, 2007 Raymond Law 1 comment

    This post shows how to use the Textile Editor Helper via Ajax so that you can retrieve the editor and update its content dynamically instead of a full page reload.

    First follow Mohit’s tutorial to build a Rails app before continuing.

    Now you are ready to add Ajax support to TEH.

    1. Include TEH support (textile-helper.js and textile-helper.css) in your layout (layouts/items.rhtml)

      <%= textile_editor_support %>

    2. Change edit.rhtml to the following

    <h1>Editing item</h1>
     
    <%= link_to_remote "Show the Ajax editor", :url => { :action => :get_ajax_editor } %>
    <div id="ajax_editor"></div>
    <div id="ajax_result"></div>
     
    <%= link_to 'Show', :action => 'show', :id => @item %> |
    <%= link_to 'Back', :action => 'list' %>

    3. Change _form.rhtml to the following

    <% remote_form_for :item, :url => { :action => :update, :id => @item } do |f| -%>
     
    <%= error_messages_for 'item' %>
     
    <!--[form:item]-->
    <p><label for="item_name">Name</label><br/>
    <%= f.text_field 'name'  %></p>
     
    <p><label for="item_descr">Descr</label><br/>
    <%= textile_editor 'item', 'descr' -%></p>
    <!--[eoform:item]-->
    <%= textile_editor_initialize -%>
     
      <%= submit_tag 'Edit' %>
    <% end -%>

    4. Add _ajax_result.rhtml

    <p><b>Name:</b> <%=h @item.name %></p>
    <p><b>Description:</b> <%= @item.descr %></p>

    5. Change items_controller.rb to the following

      def get_ajax_editor
        @item = Item.find(:first)
     
        render :update do |page|
          page.replace_html 'ajax_editor', :partial => 'form'
        end
      end
     
      def update
        @item = Item.find(params[:id])
     
        render :update do |page|
          if @item.update_attributes(params[:item])
            page.replace_html 'ajax_result', :partial => 'ajax_result', :object => @item
          else
            page.replace_html 'ajax_result', 'Item failed to be updated.'
          end
        end
      end

    Now run:

    > script/server

    Go to http://localhost:3000/items , create a new item and click on the Edit link to see how it works. Enjoy!