Apache wicket Button setMarkupId not working - java

I have:
ListView
Button
WebMarkupContainer (Popup content container)
So, when I populate the ListView, I add an AjaxEventBehavior to the buttons. I also override getAjaxCallDecorator(), as I need to call a javascript function from each button. So, in the decorateScript function, I override the WebMarkupContainer markup id by using setMarkupId(), it works. I do the same for the Button, and it works, at least when I call getMarkupId(). But when I go to the generated HTML, it's not there! Why is this happening?
The code is the following (it is inside of the populateItem from ListView):
infoBtn.add(new AjaxEventBehavior("onclick") {
#Override
protected void onEvent(AjaxRequestTarget target) {
}
#Override
protected IAjaxCallDecorator getAjaxCallDecorator() {
return new IAjaxCallDecorator() {
#Override
public CharSequence decorateScript(Component component, CharSequence script) {
StringBuilder jsScript = new StringBuilder();
infoPopoverContent.setMarkupId(infoPopoverContent.getMarkupId(true) + String.valueOf(pos));
infoBtn.setOutputMarkupPlaceholderTag(true);
infoBtn.setMarkupId(infoBtn.getMarkupId() + String.valueOf(pos));
jsScript.append("$('#" + infoBtn.getMarkupId() + "').popover({");
jsScript.append("html:true,");
jsScript.append("placement:'bottom',");
jsScript.append("content:function() {");
jsScript.append("return $('#");
jsScript.append(infoPopoverContent.getMarkupId());
jsScript.append("').html();");
jsScript.append("}");
jsScript.append("});");
logger.debug(jsScript.toString());
pos++;
return jsScript;
}
#Override
public CharSequence decorateOnSuccessScript(Component component,
CharSequence script) {
// TODO Auto-generated method stub
return null;
}
#Override
public CharSequence decorateOnFailureScript(Component component,
CharSequence script) {
// TODO Auto-generated method stub
return null;
}
};
}
});

Make sure you're calling infoBtn.setOutputMarkupId(true), so that Wicket knows it should be outputting the id attribute.
Notice setOutputMarkupPlaceholderTag(true) is also calling setOutputMarkupId(true) behind the scenes. Without knowing much about your code, it looks like you don't really need it. setOutputMarkupPlaceholderTag() will output an emtpy container (<span id="xxx"> in case the component is not visible, just to have a reference to the place the component belgons to, and allowing Wicket for manipulation via DOM in the AJAX response (for example, to make the component visible again).
As a side note, if you don't really need the id attributes to have a specific value, you can simplify your code by not using setMarkupId() and letting Wicket generate ids for you.
Also, it might be simpler to drop the IAjaxCallDecorator and just append the script in onEvent by means of AjaxRequestTarget#appendJavascript() or AjaxRequestTarget#prependJavascript(), depending on your needs.

Related

Wicket AJAX does not respond after dom changed by JavaScript

Wicket AjaxSubmitLink onSubmit is not called after applying appendJavascript which changes the DOM of a page. Sample code is:
add(new ListView("list", someArrayList){
#Override
protected void populateItem(final ListItem item) {
add(new AjaxSubmitLink("link") {
#Override
public void onClick(AjaxRequestTarget target) {
target.appendJavascript("swap('"+this.getMarkupId()+"')");
});
})
The JavaScript looks like:
function swap(markupId){
var one = $('.dashed').first().parent();
var two = $('#'+markupId).parent();
var tone = one.clone();
var ttwo = two.clone();
one.replaceWith(ttwo);
two.replaceWith(tone);
}
Any suggestions?
It might be the clone() method causing the problem. According the documentation it does not clone event handlers. Try clone(true);
You could also handle the swap server side and then rerender the list after the swap. That would be the Wicket way to do it.

GWT - how to get the tabText of selected tab?

I want to get the tab text when I click on a tab. I do this:
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
#Override
public void onSelection(SelectionEvent<Integer> event) {
//get the tabtext here
}
});
But I only get the index.
Assuming you are using TabPanel and you haven't provided a custom Widget for the TabBar, you could do this:
tabPanel.addSelectionHandler(new SelectionHandler<Integer>() {
#Override
public void onSelection(SelectionEvent<Integer> event) {
String tabHtml = tabPanel.getTabBar().getTabHTML(event.getSelectedItem());
}
});
Of course, you will get the underlying HTML of the tab, that generally is a <div>tab text</div>. The text you put in the add() methods are wrapped in either a Label, or an HTML widget, whether you have chosen to display the tab text as HTML.
Of course this is not handy, generally you need to store somewhere the tab text (in a TabPanel extension I'd guess, or a model) at insertion time (overriding the add(...)s) and retrieve it when needed (by adding a simple getter for them).
You can get the selected tab by following.
tabPanel.getElement().getTitle();

Get GWT DialogBox absolute position - onLoad/onAttach/show do not helps

I am stuck in getting an absolute position of DialogBox. I know it is the common problem (and strange workaround) for PopupPanel (which is parent to DialogBox) to set it, but what if I want to get it, what is the exact moment when the box attached to DOM? Neither overriding show nor onAttach nor show does not help:
class MyDialog extends DialogBox {
public MyDialog(. . .) {
ComplexPanel vert = new VerticalPanel();
vert.add("Test");
vert.add(new Button("Close", new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
MyDialog.this.hide();
}
}));
setWidget(vert);
this.addAttachHandler(new AttachEvent.Handler() {
#Override
public void onAttachOrDetach(AttachEvent event) {
if (event.isAttached()) Log.debug("attach:"+MyDialog.this.getAbsoluteLeft() +";"+
MyDialog.this.getAbsoluteTop());
}
});
}
#Override
protected void onLoad() {
super.onLoad();
Log.debug("load:"+this.getAbsoluteLeft() +";"+this.getAbsoluteTop());
}
#Override
public void show() {
super.show();
Log.debug("show:"+this.getAbsoluteLeft() +";"+this.getAbsoluteTop());
}
}
So when I call new MyDialog().show();, all this lines do log 0;0, however dialog is positioned in center of a page. But what I want is the sum of the chain of offsetParent positions. (And they are 0 in these moments even in JavaScript, if use JSNI to check this)
Again, setPopupPositionAndShow allows to set position but not get it :(
Finally, I've got this to work:
#Override
public void setPopupPosition(int left, int top) {
super.setPopupPosition(left, top);
if (this.isAttached()) Log.debug("setPos:"+this.getAbsoluteLeft() +";"+this.getAbsoluteTop());
}
It gets the proper position and I hope it is the right way to do it and setPopupPosition is called every time. You will even call it manually when using setPopupPositionAndShow.
I think it will be wise to let this question stay at SO "for future generations".
Upd. If you plan to call center(...) or some similar method of your dialog, be aware that setPopupPosition will be called twice or more times (may be first time with 0, 0), even if you'll check if it isAttached(). Add some additional check to ensure that positions are correct in current call.

GWT SuggestBox: How do I force the SuggestBox to select the first item in the suggestion list?

I have a textbox and one suggestbox. I attach a value change and key up handler to the text box such that whatever the user types (or pastes) into the text box is echo-ed inside the suggestbox. I can get the suggestbox to display the suggestion list by calling showSuggestionList on each value change and key up event.
Now, how do I get the suggestbox to automatically choose the first item in the suggestion list?
One of the methods I tried is to programatically simulate key presses, i.e
suggestBox.setFocus(true);
NativeEvent enterEvent = Document.get().createKeyPressEvent(false, false, false, false, KeyCodes.KEY_ENTER);
DomEvent.fireNativeEvent(enterEvent, suggestBox);
textBox.setFocus(true);
This doesn't work at all. The enter key isn't simulated. Another possible solution is to extend SuggestionBox.SuggestionDisplay, but I'm not too sure how to that. Any pointers appreciated.
Update: I'm still working on this and trying various methods.
Here, I tried to implement my own SuggestionDisplay by subclassing DefaultSuggestionDisplay and overriding getCurrentSelection() to make accessible from my class. This doesn't work either. Null is returned.
private class CustomSuggestionDisplay extends DefaultSuggestionDisplay {
#Override
protected Suggestion getCurrentSelection() {
return super.getCurrentSelection();
}
}
suggestBox.setAutoSelectEnabled(true);
textBox.addKeyUpHandler(new KeyUpHandler() {
public void onKeyUp(KeyUpEvent event) {
suggestBox.setValue(textBox.getText(), true);
suggestBox.showSuggestionList();
if (suggestBox.isSuggestionListShowing()) {
String s = ((CustomSuggestionDisplay) suggestBox.getSuggestionDisplay()).getCurrentSelection().getDisplayString();
Window.alert(s);
}
}
});
Here, I tried to attach a value change handler to the SuggestBox, and casting the event type to SuggestOracle.Suggestion. Again, null is returned.
suggestBox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
String s = ((SuggestOracle.Suggestion) event).getDisplayString();
Window.alert(s);
}
});
Use suggesBox.setAutoSelectEnabled(true)
Here more info about the SuggestBox of GWT:
You could try using addSelectionHandler in conjunction with setAutoSelectEnabled to receive an event whenever a suggestion is selected. You could also have your Oracle send a message when it suggests something, or your Display send a message when it displays a list:
public class AutomaticallySelectingSuggestionDisplay extends SuggestBox.DefaultSuggestionDisplay {
#Override
protected void showSuggestions(SuggestBox box, Collection<? extends SuggestOracle.Suggestion> suggestions, boolean isDisplayHtml, boolean isAutoSelectEnabled, SuggestBox.SuggestionCallback callback) {
super.showSuggestions(box, suggestions, isDisplayHtml, isAutoSelectEnabled, callback);
fireValueChangeEventWithFirstSuggestion(suggestions);
}
}
This idea feels a little muddled to me, so I hope you can find a solution just using event handlers.

Set focus on a component with Apache Wicket?

How do you set focus on a component with Apache Wicket? Searching leads to very little information, mostly on setting the default field. I do not want to set a default field, rather I am looking to set focus when, for example, a specific radio button is selected.
I suggest using the native org.apache.wicket.ajax.AjaxRequestTarget#focusComponent(). For example:
/**
* Sets the focus in the browser to the given component. The markup id must be set. If
* the component is null the focus will not be set to any component.
*
* #param component
* The component to get the focus or null.
*/
org.apache.wicket.ajax.AjaxRequestTarget#focusComponent(Component component)
Once you create your behavior to set the focus, you should be able to add it to the component on any event, just make sure that component is part of the AjaxRequestTarget. I don't see why this wouldn't work...
myRadioButton.add(new AjaxEventBehavior("onchange") {
#Override
protected void onEvent(AjaxRequestTarget target) {
myOtherComponent.add(new DefaultFocusBehavior());
target.addComponent(myForm);
}
});
Here's a link that shows how to create the default focus behavior if you do not have one already:
http://javathoughts.capesugarbird.com/2009/01/wicket-and-default-focus-behavior.html
If you only want to setFocus through javascript and don't want to reload a form or a component, you can use the following code:
import org.apache.wicket.Component;
public class JavascriptUtils {
private JavascriptUtils() {
}
public static String getFocusScript(Component component) {
return "document.getElementById('" + component.getMarkupId() + "').focus();";
}
}
And then in any Ajax Method you can use:
target.appendJavascript(JavascriptUtils.getFocusScript(componentToFocus));
For a pop-up like modalWindow my workaround solution was to use the attribute "autofocus" on the first input tag.
An easy solution is to add it to the html directly.
<input ..... autofocus>
Another solution is to add it to the modalWindow itself:
#Override
public void show(AjaxRequestTarget target) {
super.show(target);
setUpFocus();
}
protected void setUpFocus() {
DeepChildFirstVisitor visitor = new DeepChildFirstVisitor() {
#Override
public void component(Component component, IVisit<Void> iVisit) {
if (isAutofocusable(component)) {
component.add(new AttributeAppender("autofocus", ""));
iVisit.stop();
}
}
#Override
public boolean preCheck(Component component) {
return false;
}
};
this.visitChildren(FormComponent.class, visitor);
}
protected boolean isAutofocusable(Component component) {
if (component instanceof TextArea ||
component instanceof DropDownChoice ||
// component instanceof RadioChoice ||
component instanceof AjaxCheckBox ||
component instanceof AjaxButton ||
component instanceof TextField) {
return true;
}
return false;
}
RadioChoice is commented out because this solution is not working on that. For RadioChoice i would recommend to implement a FocusedRadioChoice:
public class FocusedRadioChoice<T> extends RadioChoice<T> {
//constructors...
#Override
protected IValueMap getAdditionalAttributes(int index, T choice) {
super.getAdditionalAttributes(0, choice);
AttributeMap am = new AttributeMap();
am.put("autofocus", "");
return am;
}
}
Is there a way to achieve the same without JavaScript?
(I am implementing a form with a feedback-Panel that only comes up when Javascript is turned off, so it would not make sense to depend on JavaScript there...,-)
I could only find answers which use JS .focs()... maybe Wicket 1.5 will provide a method Component.setFocus()...
If you happen to be using an Ajax button, you can simply call target.focusComponent(myComponent); in the button's onSubmit method.
#martin-g 's solution was the only solution that got it working for my scenario - a modal/pop up.
Note:
I think autofocus embedded explicitly in HTML only works on page load, not modal load so any efforts to skillfully set the autofocus attribute in the HTML of a modal just fail miserably - always.
Here I lay out the steps for setting the focus on an input field called 'myInput' using the full power of Wicket (no JS!):
In onInitialize:
// Make sure the field has an ID in markup
myInput.setOutoutMarkupId(true);
Provide an overridden show method where you call the focusComponent method:
public void show(AjaxRequestTarget target)
{
// Make sure you call the super method first!
super.show(target);
target.focusComponent(myInput);
}
This does require that your component is an attribute of your modal content class so that you can access it in the show method. To avoid creating a class attribute for your input component you could blend this solution with the solution from BlondCode by replacing that solution's
component.add(new AttributeAppender("autofocus", ""));
with
target.focusComponent(component);
This also works!

Categories