Topic: Using RJS to modify a nested element. Code within looking for feedback

Hi folks. Here's my scenario. I am using RJS to provide error feedback when someone is filling out a form_for. In this particular case, there are multiple instances of a model on a page (inline commenting of blog posts), which means I need to be very particular when flagging fields so that the correct field is flagged, rather than the first field on the page with that ID.

Here are two helper methods I've cooked up:

  # Page: the passed-in page object from the surrounding RJS render :update
  # Form: The form container for this instance
  # Obj: The model for the form_for
  def flag_form_fields(page, form, obj)
    prefix = obj.class.to_s.downcase + "_"
    obj.errors.each do |attr, msg|
      flag_form_field(page, form, prefix + attr)
    end
  end
 
  def flag_form_field(page, form, field)
    page.select("##{form} ##{field}").all do |element, index|
      element.addClassName "error_highlight"
    end
  end

So basically I loop through all of the model's errors, then flag the corresponding fields. What I don't like is the seemingly pointless loop in the flag_form_field method in order to get the nested element. Ideally, there'd be a mechanism similar to page['element_id'].whatever that I could ue for nested IDs, but I am drawing a blank.

Any advice appreciated. Cheers.

Re: Using RJS to modify a nested element. Code within looking for feedback

page.select("'##{form} ##{field}'") does translate to $$("#formid #fieldid") doesn't it? It returns an array which only contains one element if i get your code right.

So, the following is untested, but wouldn't this work?

page.select("'##{form} ##{field}'").first.addClassName "error_highlight"

Last edited by Duplex (2007-10-17 20:45:57)

Re: Using RJS to modify a nested element. Code within looking for feedback

Duplex, I kiss you! smile Works like a charm, cheers.

Re: Using RJS to modify a nested element. Code within looking for feedback

Welcome, and just a small comment: i would get rid of flag_form_field() unless you re-use it anywhere else, as it only contains one line, which you can easily put in the parent function

Re: Using RJS to modify a nested element. Code within looking for feedback

It is actually used elsewhere, in cases where a pure model name to form field name relationship can't be established (such as attachment_fu, which has numerous validations but only one input field).