ollitietavainen
ollitietavainen

Reputation: 4275

Vaadin TextField's value not available in shortcut listener

I want to read a Vaadin Flow TextField's value when the user presses the Enter key. I can add a ShortcutListener to listen for the keypress, but the value of the TextField is null in the listener even though the TextField is not empty: TextField textField = new TextField();

   Shortcuts.addShortcutListener(UI.getCurrent(), () -> {
     String text = texttextField.getValue();
     // text doesn't contain the latest text
   }, Key.ENTER);

Why is this happening and how can I read the value that the user has entered when the keypress listener is triggered?

Upvotes: 3

Views: 562

Answers (1)

ollitietavainen
ollitietavainen

Reputation: 4275

The behavior boils down to browser events. While the user may have entered some text into the input element, the value of the TextField is not updated to the server until there's a ValueChange event - even the vaadin-text-field element in the browser doesn't "know" of the text (the value property has not been updated) when the enter keypress event occurs. By default, the value of the text field is only updated when the input loses focus. You can work around the issue by explicitly toggling a blur of the TextField:

// member field in class
boolean shortcutFired = false;

// ...

  Shortcuts.addShortcutListener(UI.getCurrent(), () -> {
     textField.blur();
     shortcutFired = true;
  }, Key.ENTER);

and listening to the value change event instead of the shortcut listener:

textField.addValueChangeListener(e -> {
  if( shortcutFired ) { 
    String value = e.getValue();
    // do something with the value
    shortcutFired = false;
  } 
}

This approach doesn't work too well if you need to keep track of multiple fields; in that case, you might want to make the TextFields update their values to the server more eagerly by setting their ValueChangeMode to ValueChangeMode.EAGER. The downside of this approach is that it increases the amount of traffic between the browser and the network, as every keypress will trigger a server request.

Upvotes: 5

Related Questions