A page in my app displays an table of scheduled items; each row has a button
that lets the user insert a new event - a row in the table.

The 'insert row' buttons are Submits, so the whole form posts and the page
re-renders.  Because of this, it seemed important to have the form autofocus
on the field in the new row - otherwise the user might not be able to tell
which row they added (since they lose their scroll position when the page
re-renders).

This is how I did it.  I'd love to hear if there's a simpler way, it feels
like a fair number of moving parts.

MyPage.tml:

<t:form ... ><t:loop ...>
  <t:datefield t:id="eventDateField" value="currentEvent.date"
placebo="determineAutofocus()"/>
  <t:submit value="Add Row" t:id="addRow">
</t:loop></t:form>


MyPage.java:

@Environmental
private RenderSupport renderSupport;

@InjectComponent("eventDateField")
private DateField eventDateField;

@Persist
private String newlyAddedEventId;

void onSelectedFromAddRow() {
  ScheduledEvent event = new ScheduledEvent();
  event.setId( guid() );
  eventList.add(event);
  newlyAddedEventId = event.getId();
}

public String determineAutofocus() {
  if( currentEvent.getId().equals( newlyAddedEventId ) {
    renderSupport.autofocus( FieldFocusPriority.OVERRIDE,
eventDateField.getClientId() );
    newlyAddedEventId = null;
  }
  return null; // so the 'placebo' attribute doesn't get rendered
}

Michael

Reply via email to