Automatic hidden form fields and lightview
Ever needed to automatically add a hidden field in a form? Here is what I did to make it happen.
Not sure if its the best solution, but it worked for me… at least until the next rails release. ;)
In the original form_for code it creates a form tag which prints out the templates in the blog that is passed to it. There is a method that creates the opening form tag and it already creates extra_tags. All I do it add an additional concatenated string to the fields with the result of a custom method that I created called my_custom_extra_tags. Anything the method returns will be added to each form.
module ActionView::Helpers::FormTagHelper
# form_tag_html overridden on line 454 in actionpack-2.2.2/lib/action_view/helpers/form_tag_helper.rb
# original
# def form_tag_html(html_options)
# extra_tags = extra_tags_for_form(html_options)
# tag(:form, html_options, true) + extra_tags
# end
# modified
def form_tag_html(html_options)
extra_tags = extra_tags_for_form(html_options)
tag(:form, html_options, true) + extra_tags + my_custom_extra_tags
end
def my_custom_extra_tags
(params[:lightview].blank? ? '' : hidden_field_tag(:lightview, params[:lightview]))
end
end
I used this to show the same controller action with different templates and in my application controller I determine which template to show from a passed in parameter that cannot be lost or the template will revert back to the default template. Now all I have to do is pass a parameter lightview to the iframe source and the correct template will show before and after the form inside the iframe is submitted.
Hope this was helpful.

