How to add custom css class for all components where the 'required' property is true in wicket? - wicket

I'm using the jQuery validator plugin in my wicket application (wicket's version is 8.10). It uses CSS classes for identifying the validator that should be applied to the field. To mark the component as required I use the FormComponent#setRequired method. Also, I have my own components (inherited from wicket ones) in which I override the onComponentTag method like that:
#Override
protected void onComponentTag(ComponentTag tag) {
if (isRequired()) {
tag.append("class", CSS.required(), " ");
}
super.onComponentTag(tag);
}
also I use following construction for native wicket components:
if (field.isRequired()) {
field.add(new AttributeAppender("class", CSS.required()));
}
Is there any way to set this behavior for any FormComponent without overriding onCommponentTag or adding an AttributeAppender for each field object? Any global AttributeModifier or something like that?

Yes, there is:
Application.get().getOnComponentTagListeners()
.add(new IOnComponentTagListener() {
#Override
public void onComponentTag(final Component component, final ComponentTag tag) {
if (component instanceOf FormComponent) {
if (((FormComponent) component).isRequired()) {
tag.append("class", CSS.required(), " ");
}
}
}
});

Related

NatTable - how to implement custom CopyDataToClipboardSerializer

in CopyDataToClipboardSerializer I need to override copiedCells variable.
I do use NatTableFactory.class where I create table, register new CopyDataCommandHandler, override table style and so on. But I do not know how to override CopyDataToClipboardSerializer. Or should I register new one and create own class?
I don't know your NatTableFactory class. So I am not sure what you are doing inside that class.
If you need a custom serializer to for example replace line breaks in a text to a space to avoid breaking the table structure, you need to create a custom implementation and use that.
class MyCopyDataCommandHandler extends CopyDataCommandHandler {
public MyCopyDataCommandHandler(SelectionLayer selectionLayer, ILayer columnHeaderLayer, ILayer rowHeaderLayer) {
super(selectionLayer, columnHeaderLayer, rowHeaderLayer);
}
#Override
protected void internalDoCommand(CopyDataToClipboardCommand command, ILayerCell[][] assembledCopiedDataStructure) {
ISerializer serializer = new MyCopyDataToClipboardSerializer(assembledCopiedDataStructure, command);
serializer.serialize();
}
}
class MyCopyDataToClipboardSerializer extends CopyDataToClipboardSerializer {
public MyCopyDataToClipboardSerializer(ILayerCell[][] copiedCells, CopyDataToClipboardCommand command) {
super(copiedCells, command);
}
#Override
protected String getTextForCell(ILayerCell cell) {
return super.getTextForCell(cell).replace('\n', ' ');
}
}
Then register the custom MyCopyDataCommandHandler like this if the headers should be exported too:
CopyDataCommandHandler copyHandler =
new MyCopyDataCommandHandler(
selectionLayer,
columnHeaderDataLayer,
rowHeaderDataLayer);
gridLayer.registerCommandHandler(copyHandler);

Migration wicket 8.* from 7.*, problem with onRequestHandlerResolved() method on AbstractRequestCycleListener

I'm working on Wicket 8.* migration when I struggle on onRequestHandlerResolved() under IRequestCycleListener method conversion.
As per my structure of logic in my code wicket 7.15.0
public class MyRequestCycleListener extends AbstractRequestCycleListener{
//All methods override here
#Override
public void onRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler) {
if (handler instanceof ListenerInterfaceRequestHandler) {
ListenerInterfaceRequestHandler requestHandler = (ListenerInterfaceRequestHandler) handler;
if (requestHandler.getListenerInterface().getListenerInterfaceClass().isAssignableFrom( IFormSubmitListener.class)) {
//here made some login as well as every onSubmit
}
}
}
}
As wicket 8.* changes
AbstractRequestCycleListener class converts to IRequestCycleListener interface
ListenerInterfaceRequestHandler renamed to ListenerRequestHandler
Deprecates RequestListenerInterface and also IFormSubmitListener makes error
How to convert code to migration on wicket 8.9.0 ?
It should be something like this:
public class MyRequestCycleListener implements IRequestCycleListener{
#Override
public void onRequestHandlerResolved(RequestCycle cycle, IRequestHandler handler) {
if (handler instanceof ListenerRequestHandler) {
ListenerRequestHandler requestHandler = (ListenerRequestHandler) handler;
if (requestHandler.getComponent() instanceof Form) {
//here made some login as well as every onSubmit
Form form = (Form) requestHandler.getComponent();
}
}
}
}

Wicket: tell the browser to scroll to certain tag (anchor)

We are using Wicket and our generated pages are quiet long (a lot of vertical scrolling). Some links or form's onSubmit methods invoke just perform some actions on the database and show the same page again:
public class MyPage extends WebPage {
public MyPage(PageParameters parameters) {
....
final Form<Void> form = new StatelessForm<Void>("formId") {
protected void onSubmit() {
// some database stuff
...
setResponsePage(getClass(), getPageParameters());
}
};
...
}
}
How can I make the setResponsePage invocation cause the browser scroll to the form, so the page is not just showing the top? Maybe some JavaScript-injection?
I think a nice Wicket-y solution combines stuff that is already in Michael's answer, with a Behavior, so you can just add this to your form.
form.add( new ScrollToTopBehavior());
The behaviour itself would like something like this:
public class ScrollToTopBehavior extends Behavior
{
#Override
public void renderHead( Component component, IHeaderResponse response )
{
super.renderHead( component, response );
response.render( JavaScriptHeaderItem.forReference( Application.get().getJavaScriptLibrarySettings().getJQueryReference() ) );
component.setOutputMarkupId( true );
String script = String.format("doSomeJavaScriptStuff('%s')", component.getMarkupId());
response.render( OnDomReadyHeaderItem.forScript( script ) );
}
}
UPDATE:
For scrolling to a specific ID / ANCHOR only once, you can follow this answer:
https://stackoverflow.com/a/3163635/461499
JS of course.
This would be something like (with JQuery usage):
var scrollPosition = $('#scrollToMarkupId').offset().top;
$('html, body').animate({ scrollTop: " + scrollPosition + " }, 'slow');
where scrollToMarkupId is wicket component's markup id, which could be obtained by calling component.getMarkupId() method.
I'm not pro in JS, so you can try to google better impl may be.
Now, about wicket:
1) As for me, I prefer AJAX invocations for such behavior ( note that if you use such approach your page won't be stateless ):
// do not override your form's `onSubmit()` method
final Form<Void> form = new Form<Void>("formId");
// adding ajax behavior with `onSubmit()` method overriding.
form.add ( new AjaxFormSubmitBehavior ("submit")
{
protected void onSubmit ( AjaxRequestTarget target )
{
// your submit logic
// then insert js, descriped above:
target.appendJavaScript ("..." + componentToScroll.getMarkupId() + "..");
}
});
This approach won't reload your page at all but also post your data.
/----------------------------------------------------------------------------------------------------------------------------------/
2) You also could execute JS after page loading, by overriding renderHead method:
public class YourPage extends WebPage
{
...
#Override
public void renderHead ( final IHeaderResponse response )
{
//replace `...` by your script.
response.render ( OnDomReadyHeaderItem.forScript ( "..." );
}
...
}
Such script will be invoked after page is renedered (and setResponsePage method will render your page). You can use this approach for any components and panels too.
I've now use following JavaScript injecting code:
add(new Behavior() {
#Override
public void renderHead(Component component, IHeaderResponse response) {
super.renderHead(component, response);
response.render(new HeaderItem() {
#Override
public Iterable<?> getRenderTokens() {
return Collections.singletonList("javascript-anchor");
}
#Override
public void render(Response response) {
response.write("<script type=\"text/javascript\">\n");
response.write("window.location.href='#rules';\n");
response.write("</script>\n");
}
});
}
});
Feel free to comment (I'm a complete JS-noob with only very limited experience in Wicket).

How to find out component-path

I use junit to assert the existing of wicket components:
wicketTester.assertComponent("dev1WicketId:dev2WicketId:formWicketId", Form.class);
This works for some forms. For complex structure, it is defficult to find out the path of the form by searching all html files. Is there any method how to find out the path easy?
If you have the component you can call #getPageRelativePath(). E.g.
// Supposing c is a component that has been added to the page.
// Returns the full path to the component relative to the page, e.g., "path:to:label"
String pathToComponent = c.getPageRelativePath();
You can get the children of a markup container by using the visitChildren() method. The following example shows how to get all the Forms from a page.
List<Form> list = new ArrayList<Form<?>>();
Page page = wicketTester.getLastRenderedPage();
for (Form form : page.visitChildren(Form.class)) {
list.add(form);
}
An easy way to get those is to call getDebugSettings().setOutputComponentPath(true); when initializing your application. This will make Wicket to output these paths to the generated HTML as an attribute on every component-bound tag.
It's recommended to only enable this on debug mode, though:
public class WicketApplication extends WebApplication {
#Override
public void init() {
super.init();
if (getConfigurationType() == RuntimeConfigurationType.DEVELOPMENT) {
getDebugSettings().setOutputComponentPath(true);
}
}
}
Extending the RJo's answer.
It seems that the method page.visitChildren(<Class>) is deprecated (Wicket 6), so with an IVisitor it can be :
protected String findPathComponentOnLastRenderedPage(final String idComponent) {
final Page page = wicketTester.getLastRenderedPage();
return page.visitChildren(Component.class, new IVisitor<Component, String>() {
#Override
public void component(final Component component, final IVisit<String> visit) {
if (component.getId().equals(idComponent)) {
visit.stop(component.getPageRelativePath());
}
}
});
}

ClientBundle for multiple "themes"

We have a web application that needs a different theme for each major client. The original developer did this by looking at the URL in javascript and adding a stylesheet to override the default theme.
One problem with this is the site has the default look for a few seconds then suddenly swaps to the correct theme. Another is that it seems to waste a lot of bandwidth/time.
My current idea is to create a "default" ClientBundle with our default look and feel extend that interface and override each entry (as needed) with the client's images using the various annotations like #ImageResouce and pointing to a different location.
Has anybody had experience doing this? One problem I forsee is not being able to use the uibinder style tags as they statically point to a specific resource bundle.
Any ideas?
Overriden bundles
Yes you can.
I've did the override thing with ClientBundles and works fine. One thing you MUST do is inherit the types of the properties too. By example:
BigBundle {
Nestedundle otherBundle();
ImageResource otherImage();
Styles css();
}
And then you must inherit this way:
OtherBigBundle extends BigBundle {
OtherNestedBundle otherBundle(); // if you want to change it
ImageResource otherImage(); // of you want to change it
OtherStyles css(); // of you want to change it
}
and OtherNestedBundle extends NestedBundle
and OtherStyles extends Styles
At least with css's: if the properties are declared NOT USING the child interface they will produce styles for the same CSS classname and all will be mixed. So declare overriden styles with the child interfaces :)
Flexible UIBinders
You can set from outside the bundle to use if you use UiField(provided=true) annotation. In this way you first set the bundle and then call the uibindler. It will use the resource field assuming it's already created.
Deferred binding
You could use GWT.runAsync for loading just the correct bundle.
Some example
The ui.xml
<ui:with field='res' type='your.package.TheBundle'/>
the corresponding class
#UiField(provided=true) TheBundle bundle;
private void createTheThing() {
this.bundle = factory.createBundle();
MyUiBindler binder = GWT.create(MyUiBindler.class);
this.panel = binder.createAndBindUi(this);
...
}
Some bundle interfaces
interface TheBundle extends ClientBundle {
#ImageResource("default.png")
ImageResource image1();
#Source("default.css")
TheCss css();
}
interface Theme1Bundle extends TheBundle {
#ImageResource("one.png")
ImageResource image1(); // type: imageresource is ok
#Source("one.css")
OneCss css(); // type: OneCss => use other compiled css class-names
interface OneCss extends TheCss { // inner-interface, just for fun
// don't need to declare each String method
}
}
If you don't override something it's ok
Options for the bundle factory
1) just altogether
if (...) {
return GWT.create(TheBundle.class);
} else if (...) {
return GWT.create(Theme1Bundle.class);
}
2) runAsync (just load the needed part... but after the initial part is executed)
if (...) {
GWT.runAsync(new RunAsyncCallback() {
public void onSuccess() {
return GWT.create(TheBundle.class);
}
// please program the onFailure method
});
} else if (...) {
GWT.runAsync(new RunAsyncCallback() {
public void onSuccess() {
return GWT.create(Theme1Bundle.class);
}
// please program the onFailure method
});
}
3) use deferred-binding and generators for autogenerating factory in compile-time based on annotated bundles like #ThemeBundle("one")
This example is from the real world. I use a DynamicEntryPointWidgetFactory (DEPWidgetFactory for short) for creating widget based on an identifier string. Each widget is an application screen and each main menu ítem has the widgetName it has to create.
In your case the id will be the theme to create.
Important: if you use runAsync you cannot create the resourcebundle just before creating the UI like in the sample code before. You must ask for the theme and when it's ready (in the callback) pass it to your widget constructor and your widget can assign it to its field.
The factory interface:
public interface DynamicEntryPointWidgetFactory
{
public void buildWidget(String widgetName, AsyncCallback<Widget> callback);
}
The annotation for widgets to generate:
#Target(ElementType.TYPE)
public #interface EntryPointWidget
{
/**
* The name wich will be used to identify this widget.
*/
String value();
}
The module configuration:
It says: the implementation for the Factory will be generated with this class (the other option is to use replace-with, but in our case we don't have predefined options for each locale or browser, but something more dynamic).
<generate-with class="com.dia.nexdia.services.gwt.rebind.entrypoint.DynamicEntryPointFactoryGenerator">
<when-type-assignable class="com.dia.nexdia.services.gwt.client.entrypoint.DynamicEntryPointWidgetFactory" />
</generate-with>
The generator:
public class DynamicEntryPointFactoryGenerator extends Generator {
#Override
public String generate(TreeLogger logger, GeneratorContext context,
String typeName) throws UnableToCompleteException {
PrintWriter pw = context.tryCreate(logger,
"x.services.gwt.client.entrypoint",
"DynamicEntryPointWidgetFactoryImpl");
if (pw != null) {
// write package, imports, whatever
pw.append("package x.services.gwt.client.entrypoint;");
pw.append("import x.services.gwt.client.entrypoint.DynamicEntryPointWidgetFactory;");
pw.append("import com.google.gwt.core.client.GWT;");
pw.append("import com.google.gwt.core.client.RunAsyncCallback;");
pw.append("import com.google.gwt.user.client.rpc.AsyncCallback;");
pw.append("import com.google.gwt.user.client.ui.Widget;");
// the class
pw.append("public class DynamicEntryPointWidgetFactoryImpl implements DynamicEntryPointWidgetFactory {");
// buildWidget method
pw.append(" public void buildWidget(String widgetName, final AsyncCallback<Widget> callback) {");
// iterates over all the classes to find those with EntryPointWidget annotation
TypeOracle oracle = context.getTypeOracle();
JPackage[] packages = oracle.getPackages();
for (JPackage pack : packages)
{
JClassType[] classes = pack.getTypes();
for (JClassType classtype : classes)
{
EntryPointWidget annotation = classtype.getAnnotation(EntryPointWidget.class);
if (annotation != null)
{
String fullName = classtype.getQualifiedSourceName();
logger.log(TreeLogger.INFO, "Entry-point widget found: " + fullName);
pw.append("if (\"" + annotation.value() + "\".equals(widgetName)) {");
pw.append(" GWT.runAsync(" + fullName + ".class, new RunAsyncCallback() {");
pw.append(" public void onFailure(Throwable t) {");
pw.append(" callback.onFailure(t);");
pw.append(" }");
pw.append(" public void onSuccess() {");
pw.append(" callback.onSuccess(new " + fullName + "());");
pw.append(" }");
pw.append(" });");
pw.append(" return;");
pw.append("}");
}
}
}
pw.append("callback.onFailure(new IllegalArgumentException(\"Widget '\" + widgetName + \"' not recognized.\"));");
pw.append(" }");
pw.append("}");
context.commit(logger, pw);
}
// return the name of the generated class
return "x.services.gwt.client.entrypoint.DynamicEntryPointWidgetFactoryImpl";
}