I have a form with textile text, and I needed live preview. Unfortunately forms cannot be nested, so I had to make a second form. Right now I just appended it to the page, but I’ll put it in an iframe right next to the textarea later.
Here’s my code:
edit.html.erb
<% form_for @media, :html => {:id => "redclothpreview_form"}, :url => redclothpreview_admin_lesson_medias_path do |rform| %> <%= rform.submit "Redclothpreview submit" %> <% end %> <script type="text/javascript"> document.observe("dom:loaded", function() { new TryRedClothObserver('media_description', 'redclothpreview_form', 'result').parseRedcloth(); $('redclothpreview_form').hide(); }); </script> <div class="output" /> <div class="type">Text Preview</div> <div id="result"></div> </div>
tryredcloth.js
/* original code from http://redcloth.org/ */ /* since forms cannot be nested but we need a form for the ajax seperately ... hoe hoe */ var TryRedClothObserver = Class.create({ // observable: the id of some textfield to observe for changes // requestForm: the id of the form that gets submitted initialize: function(observable, requestForm, resultElement) { this.observable = $(observable); this.requestForm = $(requestForm); this.resultElement = $(resultElement); this.initObserver(); }, initObserver: function() { new Form.Element.Observer( this.observable, 0.5, // 500 milliseconds this.parseRedcloth.bind(this) ); }, parseRedcloth: function(event) { var rcObserver = this; var request_url = rcObserver.requestForm.action; //if (request_url.blank()) request_url = '/'; new Ajax.Request(request_url, { parameters: { previewtext: rcObserver.observable.value }, onSuccess: function(response) { rcObserver.resultElement.update(response.responseText); } }); } });
medias_controller.rb
def redclothpreview render :text => RedCloth.new(params[:previewtext]).to_html end
routes.rb
lesson.resources :medias, :collection => { :redclothpreview => [:post, :put] }, :has_many => :mediatypes
Note in routes.rb, it’s a put, but AJAX makes a post, so I had to add this. A common question if you google for “Only get, put, and delete requests are allowed.”
Sorry for the shitty formatting on the < and > and so forth … that’s why I use textile and not tinymce …








