MonoRail - Initial Focus ViewComponent

Need to set initial focus to a field on your form?  This component is adapted from Fábio's code on the MonoRail forums.

namespace My.Product.Mvc
{
  using Castle.MonoRail.Framework;

  [ViewComponentDetails("InitialFocus")]
  public class InitialFocusComponent : ViewComponent
  {
    private const string FOCUS_TEMPLATE =
      "<script type=\"text/javascript\">Event.observe(window,'load',function(){{$('{0}').focus();}});</script>";

    private string _id;
    private bool _shouldRender;

    [ViewComponentParam(Required=true)]
    public virtual string Id
    {
      get { return _id; }
      set { _id = value; }
    }

    public override void Initialize()
    {
      if( !Context.ContextVars.Contains("__Initial_Focus_Set__") )
      {
        Context.ContextVars["__Initial_Focus_Set__"] = Id;
        _shouldRender = true;
      }
    }

    public override void Render()
    {
      if( _shouldRender )
      {
        RenderText(string.Format(FOCUS_TEMPLATE, Id));
      }
    }
  }
}

Use in your view like so:

<% component InitialFocus, {'id':'username'} %>

This component is "first in wins" meaning if you include multiple component references in the same view/subview, the first field specified will get initial focus.  So far this has only been lightly tested on text fields.

posted @ Monday, June 25, 2007 5:41 PM


Print

Comments on this entry:

No comments posted yet.

Your comment:



 (will not be displayed)


 
 
 
Please add 6 and 7 and type the answer here:
 

Live Comment Preview:

 
«August»
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456