15

I'm using GWT and UiBinder for my app, and I'm trying to do this

<g:TextBox ui:field="searchBox" styleName="{style.searchBox}" placeholder="search" />

But the custom placeholder attribute won't work because there isn't a setPlaceholder method on TextBox - I need to this:

searchBox.getElement().setAttribute("placeholder", "search");

back in the java code. Any ideas on how to do this in UiBinder itself? I suppose I could change it over to a normal input element and try to grab a reference and its value, but I'd rather not go down that road.

Sudhir Jonathan
  • 16,998
  • 13
  • 66
  • 90
  • Afaik this is not possible (as you said, you need a setter method for it). Why not setting the attribute in the constructor of the corresponding view class right after calling `initWidget(uiBinder.createAndBindUi(this))`? Edit: or write your own placeholder functionality that will work on older browsers too. – z00bs Oct 15 '10 at 07:49
  • After `initWidget` is where I'm calling the `setAttribute` right now... I don't want to move presentation out of the XML files... – Sudhir Jonathan Oct 15 '10 at 14:25

2 Answers2

14

What about creating custom SearchBox that extends TextBox with method setPlaceholder(String placeholder) ?

Then in UiBinder:

<custom:SearchBox ui:field="searchBox" styleName="{style.searchBox}" placeholder="search" />

Andrei Volgin
  • 40,755
  • 6
  • 49
  • 58
Ilia Akhmadullin
  • 1,573
  • 1
  • 10
  • 16
  • 2
    That's probably what I'll eventually do in this case, but I see it getting more and more difficult to use HTML 5 features that are attribute based :( – Sudhir Jonathan Oct 15 '10 at 14:24
8

About a year after this was asked, I had a need to use custom attributes (placeholder, specifically). So I wrote the following custom TextField class that extends TextBox, leaving in tact all of the underlying functionality of a GWT TextBox including handlers and such. Hope someone stumbles upon this in their searches. :)

public class TextField extends TextBox {

  String placeholder = "";

  /**
   * Creates an empty text box.
   */
  public TextField() {}

  /**
   * Gets the current placeholder text for the text box.
   * 
   * @return the current placeholder text
   */
  public String getPlaceholder() {
      return placeholder;
  }

  /**
   * Sets the placeholder text displayed in the text box.
   * 
   * @param placeholder the placeholder text
   */
  public void setPlaceholder(String text) {
      placeholder = (text != null ? text : "");
      getElement().setPropertyString("placeholder", placeholder);
  }
}
Chris Cashwell
  • 22,308
  • 13
  • 63
  • 94
  • 3
    You don't need to store the placeholder as a java variable, too. You can just use the DOM value directly. – logan Nov 06 '12 at 22:47