Created
November 6, 2016 13:02
-
-
Save dim-s/9a5783bd67d55e93b8a071f51a99bc34 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
passwordField = new PasswordField("Password:"); | |
passwordField.setIcon(FontAwesome.KEY); | |
VaadinUtils.setPlaceholder(passwordField, "Enter your password"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.devlnext.portal.vaadin; | |
import com.vaadin.server.ClientConnector; | |
import com.vaadin.server.Page; | |
import com.vaadin.ui.AbstractTextField; | |
import com.vaadin.ui.JavaScript; | |
import java.util.Collection; | |
import java.util.UUID; | |
public class VaadinUtils { | |
private VaadinUtils() {} | |
private static class PlaceholderAttachListener implements ClientConnector.AttachListener { | |
private final String phClass; | |
private final String placeholder; | |
public PlaceholderAttachListener(String phClass, String placeholder) { | |
this.phClass = phClass; | |
this.placeholder = placeholder; | |
} | |
@Override | |
public void attach(ClientConnector.AttachEvent event) { | |
JavaScript js = Page.getCurrent().getJavaScript(); | |
js.execute("document.getElementsByClassName('" + phClass + "')[0].placeholder='" + placeholder.replace("'", "\\'") + "'"); | |
} | |
} | |
/** | |
* Set inputPrompt (or placeholder) via html attribute "placeholder". | |
* Also, it fixes PasswordField inputPrompt vaadin old bug. | |
*/ | |
public static void setPlaceholder(AbstractTextField textField, String placeholder) { | |
textField.setInputPrompt(null); | |
String phClass = null; | |
String[] styles = textField.getStyleName().split(" "); | |
for (String style : styles) { | |
if (style.startsWith("x-placeholder-")) { | |
phClass = style; | |
break; | |
} | |
} | |
if (phClass == null) { | |
phClass = "x-placeholder-" + UUID.randomUUID().toString(); | |
textField.addStyleName(phClass); | |
} | |
PlaceholderAttachListener attachListener = new PlaceholderAttachListener(phClass, placeholder); | |
if (textField.isAttached()) { | |
attachListener.attach(null); | |
} else { | |
Collection<?> listeners = textField.getListeners(ClientConnector.AttachListener.class); | |
listeners.stream() | |
.filter(listener -> listener instanceof PlaceholderAttachListener) | |
.forEach(listener -> textField.removeAttachListener((ClientConnector.AttachListener) listener)); | |
textField.addAttachListener(attachListener); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment