Example usage for org.apache.wicket.ajax AjaxRequestTarget prependJavaScript

List of usage examples for org.apache.wicket.ajax AjaxRequestTarget prependJavaScript

Introduction

In this page you can find the example usage for org.apache.wicket.ajax AjaxRequestTarget prependJavaScript.

Prototype

void prependJavaScript(CharSequence javascript);

Source Link

Document

Adds javascript that will be evaluated on the client side before components are replaced.

Usage

From source file:com.comcast.cdn.traffic_control.traffic_monitor.wicket.behaviors.MultiUpdatingTimerBehavior.java

License:Apache License

/**
 * Stops the timer/*from   w w w  . j  a  v a  2  s .  c  om*/
 */
public final void stop(final AjaxRequestTarget target) {
    stopped = true;
    final String timeoutHandle = getTimeoutHandle();
    target.prependJavaScript("clearTimeout(" + timeoutHandle + "); delete " + timeoutHandle + ";");
}

From source file:com.evolveum.midpoint.web.component.search.SearchPanel.java

License:Apache License

private void updateAdvancedArea(Component area, AjaxRequestTarget target) {
    Search search = getModelObject();//from   w ww  .  j a  va  2s  .co  m
    PrismContext ctx = getPageBase().getPrismContext();

    search.isAdvancedQueryValid(ctx);

    target.prependJavaScript("storeTextAreaSize('" + area.getMarkupId() + "');");
    target.appendJavaScript("restoreTextAreaSize('" + area.getMarkupId() + "');");

    target.add(get(createComponentPath(ID_FORM, ID_ADVANCED_GROUP)),
            get(createComponentPath(ID_FORM, ID_SEARCH_CONTAINER)));
}

From source file:com.mylab.wicket.jpa.ui.pages.select2.AbstractSelect2Choice.java

License:Apache License

@Override
public void onEvent(IEvent<?> event) {
    super.onEvent(event);
    if (event.getPayload() instanceof AjaxRequestTarget) {
        AjaxRequestTarget target = (AjaxRequestTarget) event.getPayload();
        if (target.getComponents().contains(this)) {

            // if this component is being repainted by ajax, directly, we
            // must destroy Select2 so it removes
            // its elements from DOM
            target.prependJavaScript(JQuery.execute("$('#%s').select2('destroy');", getJquerySafeMarkupId()));
        }/* ww  w. j  a v  a2  s  .co  m*/
    }
}

From source file:com.premiumminds.webapp.wicket.bootstrap.BootstrapModal.java

License:Open Source License

/**
 * Hide the modal. Just sends the javascript to close the modal
 *
 * @param target the AjaxRequestTarget/*  w  ww.j a  va 2s.com*/
 */
public void hide(AjaxRequestTarget target) {
    target.prependJavaScript("$('#" + getMarkupId() + "').modal('hide');");
}

From source file:com.premiumminds.webapp.wicket.repeaters.AjaxListSetView.java

License:Open Source License

private void updateAjax(AjaxRequestTarget target) {
    Set<ListSetItem<T>> newItems = new HashSet<ListSetItem<T>>();
    Set<ListSetItem<T>> removedItems = new HashSet<ListSetItem<T>>();

    updateItems(newItems, removedItems);

    for (ListSetItem<T> item : removedItems) {
        target.prependJavaScript("$('#" + item.getMarkupId() + "').remove();");
    }/*from w w w .j  a v a  2  s  . c  om*/
    for (ListSetItem<T> item : newItems) {
        String script = String.format(
                "var item = document.createElement('%s'); " + "item.id = '%s'; "
                        + "var container = Wicket.$('%s'); " + "$(container).append(item); ",
                markupTag, item.getMarkupId(), getMarkupId());
        target.prependJavaScript(script);
        target.add(item);
    }

    for (T el : getList()) {
        ListSetItem<T> item = elementToComponent.get(el);
        target.appendJavaScript("$('#" + item.getMarkupId() + "').appendTo('#" + getMarkupId() + "');");
    }
}

From source file:com.servoy.j2db.server.headlessclient.dataui.WebEventExecutor.java

License:Open Source License

@SuppressWarnings("nls")
public static void generateResponse(final AjaxRequestTarget target, Page page) {
    WebClientSession webClientSession = WebClientSession.get();
    if (target != null && page instanceof MainPage && webClientSession != null
            && webClientSession.getWebClient() != null
            && webClientSession.getWebClient().getSolution() != null) {
        if (target instanceof CloseableAjaxRequestTarget && ((CloseableAjaxRequestTarget) target).isClosed()) {
            return;
        }//  w w  w .j ava 2s  . c  o m
        // do executed the events for before generating the response.
        webClientSession.getWebClient().executeEvents();

        if (webClientSession.getWebClient() == null || webClientSession.getWebClient().getSolution() == null) {
            // how can web client be null here ?
            return;
        }
        final MainPage mainPage = ((MainPage) page);

        if (mainPage.getPageMap() instanceof ModifiedAccessStackPageMap) {
            // at every request mark the pagemap as dirty so lru eviction really works
            ((ModifiedAccessStackPageMap) mainPage.getPageMap()).flagDirty();
        }

        // If the main form is switched then do a normal redirect.
        if (mainPage.isMainFormSwitched()) {
            mainPage.versionPush();
            RequestCycle.get().setResponsePage(page);
        }

        else {
            page.visitChildren(WebTabPanel.class, new Component.IVisitor<WebTabPanel>() {
                public Object component(WebTabPanel component) {
                    component.initalizeFirstTab();
                    return IVisitor.CONTINUE_TRAVERSAL;
                }
            });

            mainPage.addWebAnchoringInfoIfNeeded();

            final Set<WebCellBasedView> tableViewsToRender = new HashSet<WebCellBasedView>();
            final List<String> valueChangedIds = new ArrayList<String>();
            final List<String> invalidValueIds = new ArrayList<String>();
            final Map<WebCellBasedView, List<Integer>> tableViewsWithChangedRowIds = new HashMap<WebCellBasedView, List<Integer>>();

            // first, get all invalidValue & valueChanged components
            page.visitChildren(IProviderStylePropertyChanges.class, new Component.IVisitor<Component>() {
                public Object component(Component component) {
                    if (component instanceof IDisplayData && !((IDisplayData) component).isValueValid()) {
                        invalidValueIds.add(component.getMarkupId());
                    }
                    if (((IProviderStylePropertyChanges) component).getStylePropertyChanges()
                            .isValueChanged()) {
                        if (component.getParent().isVisibleInHierarchy()) {
                            // the component will get added to the target & rendered only if it's parent is visible in hierarchy because changed flag is also set (see the visitor below)
                            // so we will only list these components if they are visible otherwise ajax timer could end up sending hundreds of id's that don't actually render every 5 seconds
                            // because the valueChanged flag is cleared only by onRender
                            valueChangedIds.add(component.getMarkupId());
                            if (component instanceof MarkupContainer) {
                                ((MarkupContainer) component).visitChildren(IDisplayData.class,
                                        new IVisitor<Component>() {
                                            public Object component(Component comp) {
                                                // labels/buttons that don't display data are not changed
                                                if (!(comp instanceof ILabel)) {
                                                    valueChangedIds.add(comp.getMarkupId());
                                                }
                                                return CONTINUE_TRAVERSAL;
                                            }
                                        });
                            }
                        }
                    }
                    return CONTINUE_TRAVERSAL;
                }
            });

            // add changed components to target; if a component is changed, the change check won't go deeper in hierarchy
            page.visitChildren(IProviderStylePropertyChanges.class, new Component.IVisitor<Component>() {
                public Object component(Component component) {
                    if (((IProviderStylePropertyChanges) component).getStylePropertyChanges().isChanged()) {
                        if (component.getParent().isVisibleInHierarchy()) {
                            target.addComponent(component);
                            generateDragAttach(component, target.getHeaderResponse());

                            WebForm parentForm = component.findParent(WebForm.class);
                            boolean isDesignMode = parentForm != null && parentForm.isDesignMode();

                            if (!component.isVisible() || (component instanceof WrapperContainer
                                    && !((WrapperContainer) component).getDelegate().isVisible())) {
                                ((IProviderStylePropertyChanges) component).getStylePropertyChanges()
                                        .setRendered();
                                if (isDesignMode) {
                                    target.appendJavascript("Servoy.ClientDesign.hideSelected('"
                                            + component.getMarkupId() + "')");
                                }
                            } else {
                                if (isDesignMode) {
                                    target.appendJavascript("Servoy.ClientDesign.refreshSelected('"
                                            + component.getMarkupId() + "')");
                                }
                                // some components need to perform js layout tasks when their markup is replaced when using anchored layout
                                mainPage.getPageContributor().markComponentForAnchorLayoutIfNeeded(component);
                            }

                            ListItem<IRecordInternal> row = component.findParent(ListItem.class);
                            if (row != null) {
                                WebCellBasedView wcbv = row.findParent(WebCellBasedView.class);
                                if (wcbv != null) {
                                    if (tableViewsWithChangedRowIds.get(wcbv) == null) {
                                        tableViewsWithChangedRowIds.put(wcbv, new ArrayList<Integer>());
                                    }
                                    List<Integer> ids = tableViewsWithChangedRowIds.get(wcbv);
                                    int changedRowIdx = wcbv.indexOf(row);
                                    if (changedRowIdx >= 0 && !ids.contains(changedRowIdx)) {
                                        ids.add(changedRowIdx);
                                    }
                                }
                            }
                        }
                        return IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
                    } else if (component instanceof WebCellBasedView)
                        tableViewsToRender.add((WebCellBasedView) component);
                    return component.isVisible() ? IVisitor.CONTINUE_TRAVERSAL
                            : IVisitor.CONTINUE_TRAVERSAL_BUT_DONT_GO_DEEPER;
                }
            });

            page.visitChildren(IComponentToRequestAttacher.class, new Component.IVisitor<Component>() {
                public Object component(Component component) {
                    ((IComponentToRequestAttacher) component).attachComponents(target);
                    return IVisitor.CONTINUE_TRAVERSAL;
                }
            });

            final List<String> visibleEditors = new ArrayList<String>();
            page.visitChildren(WebDataHtmlArea.class, new Component.IVisitor<Component>() {
                public Object component(Component component) {
                    visibleEditors.add(((WebDataHtmlArea) component).getEditorID());
                    return IVisitor.CONTINUE_TRAVERSAL;
                }
            });
            StringBuffer argument = new StringBuffer();
            for (String id : visibleEditors) {
                argument.append("\"");
                argument.append(id);
                argument.append("\"");
                if (visibleEditors.indexOf(id) != visibleEditors.size() - 1) {
                    argument.append(",");
                }
            }
            target.prependJavascript("Servoy.HTMLEdit.removeInvalidEditors(" + argument + ");");

            String rowSelectionScript, columnResizeScript;
            for (final WebCellBasedView wcbv : tableViewsToRender) {
                if (wcbv.isScrollMode())
                    wcbv.scrollViewPort(target, true);
                wcbv.updateRowSelection(target);
                List<Integer> changedIds = tableViewsWithChangedRowIds.get(wcbv);
                List<Integer> selectedIndexesChanged = wcbv.getIndexToUpdate(false);
                List<Integer> mergedIds = selectedIndexesChanged != null ? selectedIndexesChanged
                        : new ArrayList<Integer>();
                if (changedIds != null) {
                    for (Integer id : changedIds) {
                        if (!mergedIds.contains(id)) {
                            mergedIds.add(id);
                        }
                    }
                }
                rowSelectionScript = wcbv.getRowSelectionScript(mergedIds);
                wcbv.clearSelectionByCellActionFlag();
                if (rowSelectionScript != null)
                    target.appendJavascript(rowSelectionScript);
                columnResizeScript = wcbv.getColumnResizeScript();
                if (columnResizeScript != null)
                    target.appendJavascript(columnResizeScript);
            }

            // double check if the page contributor is changed, because the above IStylePropertyChanges ischanged could have altered it.
            if (mainPage.getPageContributor().getStylePropertyChanges().isChanged()) {
                target.addComponent((Component) mainPage.getPageContributor());
            }
            if (invalidValueIds.size() == 0) {
                target.appendJavascript("setValidationFailed(null);"); //$NON-NLS-1$
            } else {
                target.appendJavascript("setValidationFailed('" + invalidValueIds.get(0) + "');"); //$NON-NLS-1$
            }
            Component comp = mainPage.getAndResetToFocusComponent();
            if (comp != null) {
                if (comp instanceof WebDataHtmlArea) {
                    target.appendJavascript("tinyMCE.activeEditor.focus()");
                } else {
                    target.focusComponent(comp);
                }
            } else if (mainPage.getAndResetMustFocusNull()) {
                // This is needed for example when showing a non-modal dialog in IE7 (or otherwise
                // the new window would be displayed in the background).
                target.focusComponent(null);
            }
            if (valueChangedIds.size() > 0) {
                argument = new StringBuffer();
                for (String id : valueChangedIds) {
                    argument.append("\"");
                    argument.append(id);
                    argument.append("\"");
                    if (valueChangedIds.indexOf(id) != valueChangedIds.size() - 1) {
                        argument.append(",");
                    }
                }
                target.prependJavascript("storeValueAndCursorBeforeUpdate(" + argument + ");");
                target.appendJavascript("restoreValueAndCursorAfterUpdate();");
            }

            //if we have admin info, show it
            String adminInfo = mainPage.getAdminInfo();
            if (adminInfo != null) {
                adminInfo = Utils.stringReplace(adminInfo, "\r", "");
                adminInfo = Utils.stringReplace(adminInfo, "\n", "\\n");
                target.appendJavascript("alert('Servoy admin info : " + adminInfo + "');");
            }

            // If we have a status text, set it.
            String statusText = mainPage.getStatusText();
            if (statusText != null) {
                target.appendJavascript("setStatusText('" + statusText + "');");
            }

            String show = mainPage.getShowUrlScript();
            if (show != null) {
                target.appendJavascript(show);
            }

            mainPage.renderJavascriptChanges(target);

            if (((WebClientInfo) webClientSession.getClientInfo()).getProperties().isBrowserInternetExplorer()
                    && ((WebClientInfo) webClientSession.getClientInfo()).getProperties()
                            .getBrowserVersionMajor() < 9) {
                target.appendJavascript("Servoy.Utils.checkWebFormHeights();");
            }
            try {
                if (isStyleSheetLimitForIE(page.getSession())) {
                    target.appendJavascript("testStyleSheets();");
                }
            } catch (Exception e) {
                Debug.error(e);//cannot retrieve session/clientinfo/properties?
                target.appendJavascript("testStyleSheets();");
            }
        }
    }
}

From source file:com.vaynberg.wicket.select2.AbstractSelect2Choice.java

License:Apache License

@Override
public void onEvent(IEvent<?> event) {
    super.onEvent(event);

    if (event.getPayload() instanceof AjaxRequestTarget) {

        AjaxRequestTarget target = (AjaxRequestTarget) event.getPayload();

        if (target.getComponents().contains(this)) {

            // if this component is being repainted by ajax, directly, we must destroy Select2 so it removes
            // its elements from DOM

            target.prependJavaScript(JQuery.execute("$('#%s').select2('destroy');", getJquerySafeMarkupId()));
        }/*from  ww w. j  av a 2s  .co  m*/
    }
}

From source file:de.alpharogroup.wicket.components.examples.ajaxtabs.addable.AddableTabbedPanel.java

License:Apache License

public AddableTabbedPanel(final String id, final IModel<TabbedPanelModels<String>> model) {
    super(id, model);

    setDefaultModel(new CompoundPropertyModel<TabbedPanelModels<String>>(model));
    final List<TabModel<String>> tabModels = model.getObject().getTabModels();
    for (int i = 0; i < tabModels.size(); i++) {
        tabs.add(new AbstractContentTab<TabModel<String>>(tabModels.get(i).getTitle(),
                Model.of(tabModels.get(i)), Model.of("x")) {
            private static final long serialVersionUID = 1L;

            @Override/*w  w  w. j  a  v  a  2  s  . c o  m*/
            public Panel getPanel(final String panelId) {
                final Panel p = new TabPanel(panelId, getContent().getObject().getContent());
                return p;
            }
        });
    }

    add(ajaxTabbedPanel = new AjaxAddableTabbedPanel<ICloseableTab>("tabs", tabs) {
        private static final long serialVersionUID = 1L;

        @Override
        protected Component newAddTab(final String id, final IModel<String> model) {
            final WebMarkupContainer addTabContainer = new WebMarkupContainer(id);
            addTabContainer.setOutputMarkupId(true);
            addTabContainer.add(new AttributeAppender("class", " label"));
            final ModalWindow modalWindow = newAddTabModalWindow("modalWindow", Model.of("Add new tab"));
            addTabContainer.add(modalWindow);
            final AjaxLink<Void> openModal = new AjaxLink<Void>("openModal") {
                private static final long serialVersionUID = 1L;

                @Override
                public void onClick(final AjaxRequestTarget target) {
                    target.prependJavaScript("Wicket.Window.unloadConfirmation = false;");
                    modalWindow.show(target);
                }
            };
            openModal.setOutputMarkupId(true);
            openModal.add(newAddTabButtonLabel("addTabLabel", Model.of("+")));
            openModal.add(new AttributeAppender("class", " label-success"));
            addTabContainer.add(openModal);
            return addTabContainer;
        }

        @Override
        protected Label newaddTabLabel(final String id, final IModel<String> model) {
            return ComponentFactory.newLabel(id, model);
        }

        @Override
        protected IModel<String> newAddTabLabelModel() {
            return Model.of("+");
        }

        @Override
        protected ModalWindow newAddTabModalWindow(final String id, final IModel<String> model) {
            final ModalWindow modalWindow = new ModalWindow(id);
            modalWindow.setOutputMarkupId(true);
            modalWindow.setCssClassName(ModalWindow.CSS_CLASS_GRAY);
            modalWindow.setTitle(model.getObject());
            modalWindow.setInitialHeight(200);
            modalWindow.setInitialWidth(300);
            modalWindow.setContent(
                    new SaveDialogPanel<String>(modalWindow.getContentId(), Model.of(new String())) {
                        /**
                         * The serialVersionUID.
                         */
                        private static final long serialVersionUID = 1L;

                        @Override
                        protected void onCancel(final AjaxRequestTarget target, final Form<?> form) {
                            super.onCancel(target, form);
                            modalWindow.close(target);
                        }

                        @SuppressWarnings("unchecked")
                        @Override
                        protected void onSave(AjaxRequestTarget target, final Form<?> form) {
                            super.onSave(target, form);
                            if (target == null) {
                                target = ComponentFinder.findAjaxRequestTarget();
                            }
                            final Object value = getModel();
                            String v = null;
                            if (value instanceof IModel) {
                                final Object obj = ((IModel<?>) value).getObject();
                                if (obj instanceof String) {
                                    v = (String) obj;
                                }
                            }
                            target.add(ajaxTabbedPanel);

                            final TabModel<String> newTabModel = new TabModel<>(Model.of(v), Model.of(v),
                                    Model.of("x"));

                            final AbstractContentTab<TabModel<String>> tab = new AbstractContentTab<TabModel<String>>(
                                    newTabModel.getTitle(), Model.of(newTabModel), Model.of("x")) {
                                private static final long serialVersionUID = 1L;

                                @Override
                                public Panel getPanel(final String panelId) {
                                    final Panel p = new TabPanel(panelId,
                                            getContent().getObject().getContent());
                                    return p;
                                }
                            };
                            final Object object = AddableTabbedPanel.this.getDefaultModelObject();
                            final TabbedPanelModels<String> tabbedModel = (TabbedPanelModels<String>) object;
                            final List<TabModel<String>> tabModels = tabbedModel.getTabModels();
                            tabModels.add(newTabModel);
                            ajaxTabbedPanel.onNewTab(target, tab);
                            modalWindow.close(target);
                        }
                    });
            return modalWindow;
        }

        @Override
        protected WebMarkupContainer newCloseLink(final String linkId, final int index) {
            final WebMarkupContainer wmc = super.newCloseLink(linkId, index);
            wmc.add(new AttributeAppender("class", "close label label-warning"));
            return wmc;

        }

        @Override
        protected WebMarkupContainer newLink(final String linkId, final int index) {
            final WebMarkupContainer wmc = super.newLink(linkId, index);
            wmc.add(new AttributeAppender("class", "label label-success"));
            return wmc;
        }
    });
}

From source file:de.alpharogroup.wicket.components.examples.notifications.NotificationExamplesPanel.java

License:Apache License

public NotificationExamplesPanel(final String id, final IModel<?> model) {
    super(id, model);
    final IModel<String> labelModel = ResourceModelFactory.newResourceModel(
            ResourceBundleKey.builder().key("button.toastr.label").defaultValue("Show toastr notice.").build(),
            this);
    final Form<Object> form = new Form<Object>("form");
    add(form);//from   w  w  w . j a  v a2s  .com
    form.add(new ButtonPanel("toastrButtonPanel", labelModel, form) {

        /**
         * The serialVersionUID
         */
        private static final long serialVersionUID = 1L;

        @Override
        protected Button newButton(final String id) {
            final IndicatingAjaxButton indicatingAjaxButton = new IndicatingAjaxButton(id, getForm()) {
                /**
                 * The serialVersionUID.
                 */
                private static final long serialVersionUID = 1L;

                @Override
                protected void onError(final AjaxRequestTarget target, final Form<?> form) {
                }

                @Override
                protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
                    target.add(form);
                    final ToastJsGenerator jsGenerator = new ToastJsGenerator();

                    final ToastrSettings settings = jsGenerator.getSettings();
                    settings.getPositionClass().setValue(Position.TOP_RIGHT);
                    settings.getNotificationContent().setValue("This is a notification");
                    final String js = jsGenerator.generateJs();
                    target.prependJavaScript(js);
                }
            };
            indicatingAjaxButton.add(new AttributeAppender("class", Model.of(" btn btn-primary")));
            return indicatingAjaxButton;
        }
    });
    final IModel<String> pnotifyLabelModel = ResourceModelFactory.newResourceModel(
            ResourceBundleKey.builder().key("button.label").defaultValue("Show pnotify notice.").build(), this);
    form.add(new ButtonPanel("pnotifyButtonPanel", pnotifyLabelModel, form) {

        /**
         * The serialVersionUID
         */
        private static final long serialVersionUID = 1L;

        @Override
        protected Button newButton(final String id) {
            final IndicatingAjaxButton indicatingAjaxButton = new IndicatingAjaxButton(id, getForm()) {
                /**
                 * The serialVersionUID.
                 */
                private static final long serialVersionUID = 1L;

                @Override
                protected void onError(final AjaxRequestTarget target, final Form<?> form) {
                }

                @Override
                protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
                    target.add(form);
                    final PnotifySettings pnotifySettings = PnotifySettings.builder().build();
                    pnotifySettings.getTitle().setValue("Test title");
                    pnotifySettings.getText().setValue("a text");
                    final PnotifyJsGenerator pnotifyJsGenerator = new PnotifyJsGenerator(pnotifySettings);
                    final String js = pnotifyJsGenerator.generateJs();
                    target.prependJavaScript(js);
                }
            };
            indicatingAjaxButton.add(new AttributeAppender("class", Model.of(" btn btn-primary")));
            return indicatingAjaxButton;
        }
    });
}

From source file:de.alpharogroup.wicket.dialogs.ajax.modal.ModalDialogFragmentPanel.java

License:Apache License

/**
 * Callback method to hang on when the dialog is open.
 *
 * @param target//ww  w .j  av  a  2  s. c  om
 *            the ajax request target.
 */
protected void onShow(final AjaxRequestTarget target) {
    /**
     * This is how to prevent IE and Firefox dialog popup when trying to setResponsePage() or
     * set an info message from a wicket modalWindow per below. Dialog popup demands an answer
     * to: "This page is asking you to confirm that you want to leave - data you have entered
     * may not be saved."
     **/
    target.prependJavaScript(WICKET_WINDOW_UNLOAD_CONFIRMATION_FALSE_JS);
    getModalWindow().show(target);
}