/**
   * Defines an {@link AddCommentPanel} object of a file or an album, either album or file must be
   * null, but not both.
   *
   * @param id This panel {@code wicket:id}
   * @param commentsPanel Comment panel, to reload it on adding comments, it can be {@code null}
   * @param album The {@link #album}, or {@code null} for a file panel
   * @param file The {@link #file}, or {@code null} for an album panel
   */
  private AddCommentPanel(String id, ShowCommentsPanel commentsPanel, Album album, File file) {
    super(id);
    this.album = album;
    this.file = file;

    final ShowCommentsPanel showCommentsPanel = commentsPanel;
    final TextArea<String> text = new TextArea<String>("text", Model.of(""));
    text.setRequired(true);

    Form<Void> form =
        new Form<Void>("addCommentForm") {
          @Override
          protected void onSubmit() {
            String textString = cleanComment(text.getModelObject());
            if (validateComment(textString)) {
              createComment(textString);
              if (showCommentsPanel != null) {
                showCommentsPanel.reload();
              }
            }
            setResponsePage(this.getPage());
          }
        };
    add(form);
    form.add(text);
    form.add(new Label("maxLength", String.valueOf(Comment.MAX_TEXT_LENGTH)));
  }
    public CommentForm(String id, final Thread thread) {
      super(id);

      name = new TextArea("name", new PropertyModel(properties, "name"));
      name.setRequired(true);
      name.add(StringValidator.maximumLength(500));
      name.setLabel(new Model("Text"));
      add(name);
      add(new Label("nameLabel", "Text"));

      add(
          submit =
              new Button("submit", new ResourceModel("button.submit")) {

                public void onSubmit() {

                  Comment comment = new Comment();

                  comment.setName(name.getModelObjectAsString());
                  comment.setThread(thread);
                  comment.setOwner(user);

                  // not user input

                  comment.setActive(true);
                  comment.setState(true);

                  commentController.saveNewComment(comment);
                  name.setModelValue("");
                  setResponsePage(new CommentList(thread));
                  feedbackPanel.info("Vlo�en�");
                }
              });
    }
  @Override
  protected void onInitialize() {
    super.onInitialize();
    News pieceOfNews = getModelObject();
    if (pieceOfNews == null) {
      pieceOfNews = new News();
    }

    /* Add Form to add News */
    final ValidatableForm<News> createOrUpdateNews =
        new ValidatableForm<News>("addNews", new CompoundPropertyModel<News>(pieceOfNews));
    createOrUpdateNews.setOutputMarkupId(true);
    add(createOrUpdateNews);

    /* Add editor to decide text of the piece of News. */
    WebMarkupContainer descriptionWrapper = new WebMarkupContainer("newsWrapper");
    createOrUpdateNews.add(descriptionWrapper);
    TextArea description = (TextArea) new TextArea<String>("text").setRequired(true);
    description.add(new CSLDTinyMceBehavior());
    descriptionWrapper.add(description);
    descriptionWrapper.add(
        new CsldFeedbackMessageLabel(
            "newsFeedback", description, descriptionWrapper, "form.news.textHint"));

    List<String> availableLanguages = new ArrayList<String>(availableLocaleNames());
    final DropDownChoice<String> lang = new DropDownChoice<String>("lang", availableLanguages);
    createOrUpdateNews.add(lang);
    createOrUpdateNews.add(new CsldFeedbackMessageLabel("langFeedback", lang, null));

    /* Add button to create news piece. */
    createOrUpdateNews
        .add(
            new AjaxButton("submit") {
              @Override
              protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                super.onSubmit(target, form);

                if (createOrUpdateNews.isValid()) {
                  News pieceOfNews = createOrUpdateNews.getModelObject();
                  if (news.saveOrUpdate(pieceOfNews)) {
                    onCsldAction(target, form);
                  }
                }
              }

              @Override
              protected void onError(AjaxRequestTarget target, Form<?> form) {
                super.onError(target, form);

                target.add(form);
              }
            })
        .add(new TinyMceAjaxSubmitModifier());

    if (isSignedIn()) {
      add(new JSPingBehavior());
    }
  }
  /**
   * Alpha of Yui SimpleEditor - note that it uses the YuiLoader and that these 2 components (Loader
   * + Editor) are BETA status from YUI!
   *
   * @param id
   * @param model
   */
  public YuiSimpleEditor(String id, IModel model) {
    super(id);

    String jsInit = getInitJs();

    add(YuiLoaderHeaderContributor.forModule("simpleeditor", jsInit));
    TextArea ta = new TextArea("editorArea", model);
    ta.setEscapeModelStrings(false);
    add(ta);
  }
  /** Test creation with no default. */
  @Test
  public void testCreation_nodefault() {
    tester.startPage(getTestPage());
    @SuppressWarnings("unchecked")
    TextArea<String> tf = (TextArea<String>) getTestSubject();
    Assert.assertNull(tf.getModelObject());
    Assert.assertFalse(getFeedbackPanel().anyErrorMessage());

    Assert.assertFalse(tester.getLastResponse().getDocument().contains(MarkupConstants.READONLY));
  }
Beispiel #6
0
  public CustomerFormPanel(String id, CompoundPropertyModel<CustomerAdminBackingBean> model) {
    super(id, model);

    GreySquaredRoundedBorder greyBorder = new GreySquaredRoundedBorder("border");
    add(greyBorder);

    setOutputMarkupId(true);

    final Form<CustomerAdminBackingBean> form =
        new Form<CustomerAdminBackingBean>("customerForm", model);

    // name
    RequiredTextField<String> nameField = new RequiredTextField<String>("customer.name");
    form.add(nameField);

    nameField.add(StringValidator.lengthBetween(0, 64));
    nameField.setLabel(new ResourceModel("admin.customer.name"));
    nameField.add(new ValidatingFormComponentAjaxBehavior());
    form.add(new AjaxFormComponentFeedbackIndicator("nameValidationError", nameField));

    // code
    final RequiredTextField<String> codeField = new RequiredTextField<String>("customer.code");
    form.add(codeField);
    codeField.add(StringValidator.lengthBetween(0, 16));
    codeField.setLabel(new ResourceModel("admin.customer.code"));
    codeField.add(new ValidatingFormComponentAjaxBehavior());
    form.add(new UniqueCustomerValidator(nameField, codeField));
    form.add(new AjaxFormComponentFeedbackIndicator("codeValidationError", codeField));

    // description
    TextArea<String> textArea = new KeepAliveTextArea("customer.description");
    textArea.setLabel(new ResourceModel("admin.customer.description"));
    form.add(textArea);

    // active
    form.add(new CheckBox("customer.active"));

    // data save label
    form.add(new ServerMessageLabel("serverMessage", "formValidationError"));

    //

    boolean deletable = model.getObject().getCustomer().isDeletable();
    FormConfig formConfig =
        new FormConfig()
            .forForm(form)
            .withDelete(deletable)
            .withSubmitTarget(this)
            .withDeleteEventType(CustomerAjaxEventType.CUSTOMER_DELETED)
            .withSubmitEventType(CustomerAjaxEventType.CUSTOMER_UPDATED);

    FormUtil.setSubmitActions(formConfig);

    greyBorder.add(form);
  }
  private void setFormFieldsFromQuestion(Question question) {
    Answer.AnswerType aType = question.getAnswerType();

    questionTitleField.setModelObject(question.getTitle());
    questionPromptField.setModelObject(question.getPrompt());
    questionPrefaceField.setModelObject(question.getPreface());
    questionCitationField.setModelObject(question.getCitation());
    questionResponseTypeModel.setObject(question.getAnswerType());
    Long answerReasonId = question.getAnswerReasonExpressionId();
    questionAnswerReasonModel.setObject(
        answerReasonId == null ? answerAlways : Expressions.get(answerReasonId));
    String msg = "Asking style in setFormFields: " + askingStyleModel.getObject();
    askingStyleModel.setObject(question.getAskingStyleList());
    msg +=
        " -> "
            + askingStyleModel.getObject()
            + " (question had "
            + question.getAskingStyleList()
            + ")";
    // throw new RuntimeException(msg);
    // questionUseIfField.setModelObject(question.getUseIfExpression());
    otherSpecifyCheckBox.setModelObject(question.getOtherSpecify());
    noneButtonCheckBox.setModelObject(question.getNoneButton());
    if (aType == Answer.AnswerType.NUMERICAL) {
      numericLimitsPanel.setVisible(true);
    } else if (aType == Answer.AnswerType.MULTIPLE_SELECTION) {
      multipleSelectionLimitsPanel.setVisible(true);
      noneButtonLabel.setVisible(true);
      noneButtonCheckBox.setVisible(true);
    }
    if (aType == Answer.AnswerType.SELECTION || aType == Answer.AnswerType.MULTIPLE_SELECTION) {
      otherSpecifyLabel.setVisible(true);
      otherSpecifyCheckBox.setVisible(true);
    } else {
      otherSpecifyLabel.setVisible(false);
      otherSpecifyCheckBox.setVisible(false);
    }
    if (aType == Answer.AnswerType.DATE || aType == Answer.AnswerType.TIME_SPAN) {
      timeUnitsPanel.setVisible(true);
    } else {
      timeUnitsPanel.setVisible(false);
    }
    numericLimitsPanel.setMinLimitType(question.getMinLimitType());
    numericLimitsPanel.setMinLiteral(question.getMinLiteral());
    numericLimitsPanel.setMinPrevQues(question.getMinPrevQues());
    numericLimitsPanel.setMaxLimitType(question.getMaxLimitType());
    numericLimitsPanel.setMaxLiteral(question.getMaxLiteral());
    numericLimitsPanel.setMaxPrevQues(question.getMaxPrevQues());

    multipleSelectionLimitsPanel.setMinCheckableBoxes(question.getMinCheckableBoxes());
    multipleSelectionLimitsPanel.setMaxCheckableBoxes(question.getMaxCheckableBoxes());

    listLimitsPanel.setQuestion(question);
  }
  /** Test creation with default value. */
  @Test
  public void testCreation_withDefault() {
    descriptor.setHasDefault(true);
    descriptor.setDefaultValue(StringConstants.EMPTY);
    tester.startPage(getTestPage());
    @SuppressWarnings("unchecked")
    TextArea<String> tf = (TextArea<String>) getTestSubject();
    Assert.assertNotNull(tf.getModelObject());
    Assert.assertEquals(StringConstants.EMPTY, tf.getModelObject());
    Assert.assertFalse(getFeedbackPanel().anyErrorMessage());

    Assert.assertFalse(tester.getLastResponse().getDocument().contains(MarkupConstants.READONLY));
  }
Beispiel #9
0
  public CKEditorPanel(
      final String id, final String editorConfigJson, final IModel<String> editModel) {
    super(id);

    this.editorConfigJson = editorConfigJson;

    final TextArea<String> textArea = new TextArea<String>(WICKET_ID_EDITOR, editModel);
    textArea.setOutputMarkupId(true);
    add(textArea);

    editorId = textArea.getMarkupId();

    extensions = new LinkedList<CKEditorPanelExtension>();
  }
 private void insertFormFieldsIntoQuestion(Question question) {
   question.setTitle((String) questionTitleField.getModelObject());
   question.setPrompt((String) questionPromptField.getModelObject());
   question.setPreface((String) questionPrefaceField.getModelObject());
   question.setCitation((String) questionCitationField.getModelObject());
   question.setAnswerType((Answer.AnswerType) questionResponseTypeModel.getObject());
   Object answerReason = questionAnswerReasonModel.getObject();
   question.setAnswerReasonExpressionId(
       answerReason == null || answerReason.equals(answerAlways)
           ? null
           : ((Expression) answerReason).getId());
   Boolean askingStyle = (Boolean) askingStyleModel.getObject();
   String msg =
       "Asking style in insertFormFields (model="
           + askingStyle
           + "): "
           + question.getAskingStyleList();
   question.setAskingStyleList(askingStyle); // TODO: need to trace what happens in this method
   msg += " -> " + question.getAskingStyleList();
   // throw new RuntimeException(msg);
   /// question.setUseIfExpression((String) questionUseIfField.getModelObject());
   question.setOtherSpecify((Boolean) otherSpecifyCheckBox.getModelObject());
   question.setNoneButton((Boolean) noneButtonCheckBox.getModelObject());
   question.setTimeUnits((Integer) timeUnitsPanel.getTimeUnits());
   if (question.getAnswerType() == Answer.AnswerType.NUMERICAL) {
     question.setMinLimitType(numericLimitsPanel.getMinLimitType());
     question.setMinLiteral(numericLimitsPanel.getMinLiteral());
     question.setMinPrevQues(numericLimitsPanel.getMinPrevQues());
     question.setMaxLimitType(numericLimitsPanel.getMaxLimitType());
     question.setMaxLiteral(numericLimitsPanel.getMaxLiteral());
     question.setMaxPrevQues(numericLimitsPanel.getMaxPrevQues());
   } else if (question.getAnswerType() == Answer.AnswerType.MULTIPLE_SELECTION) {
     question.setMinCheckableBoxes(multipleSelectionLimitsPanel.getMinCheckableBoxes());
     question.setMaxCheckableBoxes(multipleSelectionLimitsPanel.getMaxCheckableBoxes());
   }
   if (askingStyle) {
     question.setWithListRange(listLimitsPanel.getWithListRange());
     question.setListRangeString(listLimitsPanel.getListRangeString());
     question.setMinListRange(listLimitsPanel.getMinListRange());
     question.setMaxListRange(listLimitsPanel.getMaxListRange());
   }
 }
Beispiel #11
0
  @Test
  public void testRenderEditXmlView() {
    PageParameters pageParameters = new PageParameters();
    pageParameters.set(VIEW.toString(), "xml");
    pageParameters.set(EDIT_MODE.toString(), true);
    pageParameters.set(CURRENT_UUID.toString(), shsProduct.getUuid());

    tester.startPage(EditProductPage.class, pageParameters);

    tester.assertNoErrorMessage();
    tester.assertComponent("productPanel:feedback", FeedbackPanel.class);
    tester.assertComponent("productPanel:productForm", Form.class);
    tester.assertComponent("productPanel:productForm:uuid", HiddenField.class);
    tester.assertComponent("productPanel:productForm:control.xml:xml", TextArea.class);

    final TextArea<String> xmlField =
        (TextArea<String>)
            tester.getComponentFromLastRenderedPage("productPanel:productForm:control.xml:xml");
    assertThat(xmlField.getValue(), containsString(shsProduct.getUuid()));
  }
 @SuppressWarnings("serial")
 public void redraw() {
   clearContent();
   {
     gridBuilder.newSecurityAdviceBox(Model.of(getString("calendar.icsExport.securityAdvice")));
     addFormFields();
     final FieldsetPanel fs =
         gridBuilder.newFieldset(getString("calendar.abonnement.url")).setLabelSide(false);
     urlTextArea =
         new TextArea<String>(
             fs.getTextAreaId(),
             new Model<String>() {
               @Override
               public String getObject() {
                 return WicketUtils.getAbsoluteContextPath() + getUrl();
               };
             });
     urlTextArea.setOutputMarkupId(true);
     fs.add(urlTextArea);
     urlTextArea.add(AttributeModifier.replace("onClick", "$(this).select();"));
   }
 }
 @Override
 public void renderHead(IHeaderResponse response) {
   super.renderHead(response);
   JavaScriptUrlReferenceHeaderItem item =
       new JavaScriptUrlReferenceHeaderItem(
           "http://cdn.ckeditor.com/4.5.9/full/ckeditor.js", "ckeditor", false, "UTF-8", "");
   response.render(item);
   String javascript =
       "CKEDITOR.replace( '"
           + getMarkupId(true)
           + "', {toolbar: [[ 'Bold', 'Italic','Underline' ],['TextColor', 'BGColor','SpecialChar' ]]})";
   response.render(OnDomReadyHeaderItem.forScript(javascript));
 }
Beispiel #14
0
  /** Test creation with regular expression. */
  @Test
  public void testCreation_withExpression() {
    String expression = "[^b]at"; // $NON-NLS-1$
    descriptor.setExpression(expression);
    tester.startPage(getTestPage());

    @SuppressWarnings("unchecked")
    TextArea<String> tf = (TextArea<String>) getTestSubject();

    tf.setDefaultModelObject("bat"); // $NON-NLS-1$

    FormTester ft = tester.newFormTester(TestPage.FORM_ID);
    ft.submit();

    Assert.assertTrue(getFeedbackPanel().anyErrorMessage());
    List<FeedbackMessage> messages = getFeedbackPanel().getFeedbackMessagesModel().getObject();
    Assert.assertEquals(1, messages.size());
    String msg = messages.get(0).toString();
    Assert.assertTrue(msg.contains(expression));

    Assert.assertFalse(tester.getLastResponse().getDocument().contains(MarkupConstants.READONLY));
  }
  public EditableSettingsModalPanel(final DownloadModalSettings settings) {
    contentTextArea = new TextArea<String>("content", Model.<String>of(settings.getContent()));
    contentTextArea.setOutputMarkupId(true);

    FilteredResourcesWebAddon filteredResourcesWebAddon =
        addonsManager.addonByType(FilteredResourcesWebAddon.class);
    String saveToFileName = settings.getSaveToFileName();
    form.add(
        filteredResourcesWebAddon.getSettingsProvisioningBorder(
            "settingsProvisioning", form, contentTextArea, saveToFileName));

    final AjaxSettingsDownloadBehavior ajaxSettingsDownloadBehavior =
        new AjaxSettingsDownloadBehavior(saveToFileName) {

          @Override
          protected StringResourceStream getResourceStream() {
            FilteredResourcesWebAddon filteredResourcesWebAddon =
                addonsManager.addonByType(FilteredResourcesWebAddon.class);
            try {
              String filtered =
                  filteredResourcesWebAddon.filterResource(
                      null,
                      (Properties) InfoFactoryHolder.get().createProperties(),
                      new StringReader(contentTextArea.getModelObject()));
              return new StringResourceStream(filtered, settings.getSettingsMimeType());
            } catch (Exception e) {
              log.error("Unable to filter settings: " + e.getMessage());
              return new StringResourceStream(
                  contentTextArea.getModelObject(), settings.getSettingsMimeType());
            }
          }
        };

    form.add(ajaxSettingsDownloadBehavior);

    Component exportLink =
        new TitledAjaxSubmitLink("export", settings.getDownloadButtonTitle(), form) {
          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            ajaxSettingsDownloadBehavior.initiate(target);
          }
        };
    exportLink.add(new CssClass(new DefaultButtonStyleModel(exportLink)));
    add(exportLink);

    setWidth(700);
    add(new ModalCloseLink("cancel", "Cancel"));

    addContentToBorder();
  }
  private void constructPanel() {
    final Form<?> form =
        new Form("messageForm", new CompoundPropertyModel<NotificationMessagePanel>(this));
    final WebMarkupContainer emailTextContainer = new WebMarkupContainer("emailTextContainer");
    final WebMarkupContainer smsTextContainer = new WebMarkupContainer("smsTextContainer");
    final WebMarkupContainer confidentialTextContainer =
        new WebMarkupContainer("confidentialTextContainer");
    form.add(new FeedbackPanel("errorMessages"));
    form.add(
        new RequiredTextField<String>("message.name")
            .add(Constants.mediumStringValidator)
            .add(Constants.mediumSimpleAttributeModifier)
            .add(new ErrorIndicator())
            .setEnabled(isCreateMode));
    final LocalizableLookupDropDownChoice<String> templateTypeDropDown =
        new LocalizableLookupDropDownChoice<String>(
            "message.templateType",
            String.class,
            Constants.RESOURCE_BUNDLE_TEMPLATE_TYPE,
            basePage,
            Boolean.FALSE,
            true);
    templateTypeDropDown.setNullValid(false).setRequired(true).setEnabled(isCreateMode);

    templateTypeDropDown.add(
        new AjaxFormComponentUpdatingBehavior("onchange") {
          private static final long serialVersionUID = 1L;

          @Override
          protected void onUpdate(AjaxRequestTarget target) {
            String newSelection = templateTypeDropDown.getModelObject();
            if (Constants.TEMPLATE_TYPE_EMAIL_KEY.equals(newSelection)) {
              emailTextContainer.setVisible(true);
              smsTextContainer.setVisible(false);
            } else {
              emailTextContainer.setVisible(false);
              smsTextContainer.setVisible(true);
            }
            target.addComponent(emailTextContainer);
            target.addComponent(smsTextContainer);
          }
        });
    form.add(templateTypeDropDown);
    form.add(
        new TextField<String>("localeStr")
            .add(new PatternValidator(Constants.REGEX_LOCALE_VARIANT))
            .add(new ErrorIndicator())
            .setEnabled(isCreateMode));
    form.add(
        new RequiredTextField<String>("message.sender")
            .add(Constants.mediumStringValidator)
            .add(Constants.mediumSimpleAttributeModifier)
            .add(new ErrorIndicator()));
    smsTextContainer.add(
        new TextArea<String>("smsText").setRequired(true).add(new ErrorIndicator()));
    smsTextContainer.setOutputMarkupPlaceholderTag(true).setVisible(!isEmail);
    form.add(smsTextContainer);
    emailTextContainer.add(
        new TextField<String>("message.subject")
            .setRequired(true)
            .add(Constants.mediumStringValidator)
            .add(Constants.mediumSimpleAttributeModifier)
            .add(new ErrorIndicator()));
    emailTextContainer.add(
        new TextArea<String>("plainText").setRequired(true).add(new ErrorIndicator()));
    emailTextContainer.add(new TextArea<String>("htmlText").add(new ErrorIndicator()));
    emailTextContainer.setOutputMarkupPlaceholderTag(true).setVisible(isEmail);
    form.add(emailTextContainer);
    final AjaxCheckBox confidentialCheckBox =
        new AjaxCheckBox("message.confidential") {

          @Override
          protected void onUpdate(AjaxRequestTarget target) {
            boolean selected = getModelObject();
            if (selected) confidentialTextContainer.setVisible(true);
            else confidentialTextContainer.setVisible(false);
            target.addComponent(confidentialTextContainer);
          }
        };
    final TextArea confidentialTextArea = new TextArea<String>("message.logText");
    form.add(confidentialCheckBox.add(new ErrorIndicator()));
    confidentialTextContainer.add(confidentialTextArea.add(new ErrorIndicator()));
    form.add(
        confidentialTextContainer
            .setOutputMarkupPlaceholderTag(true)
            .setVisible(
                (message != null && message.isConfidential() != null)
                    ? message.isConfidential()
                    : false));
    createAttachmentContainer(form);

    form.add(
        new Button("submit") {
          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            createMessage();
          }
        });
    form.add(
        new Button("export") {
          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            exportMessage();
          }
        }.setDefaultFormProcessing(false).setVisible(!isCreateMode));
    form.add(
        new Button("test") {
          private static final long serialVersionUID = 1L;

          @Override
          public void onSubmit() {
            sendTestMessageRequest();
          }
        }.setDefaultFormProcessing(false).setVisible(!isCreateMode));
    add(form);
  }
 @Override
 protected void onInitialize() {
   super.onInitialize();
   setOutputMarkupId(true);
 }
  public ComposeNewMessage(String id) {
    super(id);

    // current user
    final String userId = sakaiProxy.getCurrentUserId();

    // setup model
    NewMessageModel newMessage = new NewMessageModel();
    newMessage.setFrom(userId);

    // feedback for form submit action
    formFeedback = new Label("formFeedback");
    formFeedback.setOutputMarkupPlaceholderTag(true);
    add(formFeedback);

    // setup form
    final Form<NewMessageModel> form =
        new Form<NewMessageModel>("form", new Model<NewMessageModel>(newMessage));

    // close button
    /*
    WebMarkupContainer closeButton = new WebMarkupContainer("closeButton");
    closeButton.add(new AjaxFallbackLink<Void>("link") {
    	private static final long serialVersionUID = 1L;

    	public void onClick(AjaxRequestTarget target) {
    		if(target != null) {
    			target.prependJavascript("$('#" + thisPanel.getMarkupId() + "').slideUp();");
    			target.appendJavascript("setMainFrameHeight(window.name);");
    		}
    	}
    }.add(new ContextImage("img",new Model<String>(ProfileConstants.CLOSE_IMAGE))));
    form.add(closeButton);
    */

    // to label
    form.add(new Label("toLabel", new ResourceModel("message.to")));

    // get connections
    final List<Person> connections = connectionsLogic.getConnectionsForUser(userId);
    Collections.sort(connections);

    // list provider
    AutoCompletionChoicesProvider<Person> provider =
        new AutoCompletionChoicesProvider<Person>() {
          private static final long serialVersionUID = 1L;

          public Iterator<Person> getChoices(String input) {
            return connectionsLogic
                .getConnectionsSubsetForSearch(connections, input, true)
                .iterator();
          }
        };

    // renderer
    ObjectAutoCompleteRenderer<Person> renderer =
        new ObjectAutoCompleteRenderer<Person>() {
          private static final long serialVersionUID = 1L;

          protected String getIdValue(Person p) {
            return p.getUuid();
          }

          protected String getTextValue(Person p) {
            return p.getDisplayName();
          }
        };

    // autocompletefield builder
    ObjectAutoCompleteBuilder<Person, String> builder =
        new ObjectAutoCompleteBuilder<Person, String>(provider);
    builder.autoCompleteRenderer(renderer);
    builder.searchLinkImage(ResourceReferences.CROSS_IMG_LOCAL);
    builder.preselect();

    // autocompletefield
    final ObjectAutoCompleteField<Person, String> autocompleteField =
        builder.build("toField", new PropertyModel<String>(newMessage, "to"));
    toField = autocompleteField.getSearchTextField();
    toField.setMarkupId("messagerecipientinput");
    toField.setOutputMarkupId(true);
    toField.add(new AttributeModifier("class", true, new Model<String>("formInputField")));
    toField.setRequired(true);
    form.add(autocompleteField);

    // subject
    form.add(new Label("subjectLabel", new ResourceModel("message.subject")));
    final TextField<String> subjectField =
        new TextField<String>("subjectField", new PropertyModel<String>(newMessage, "subject"));
    subjectField.setMarkupId("messagesubjectinput");
    subjectField.setOutputMarkupId(true);
    subjectField.add(new RecipientEventBehavior("onfocus"));
    form.add(subjectField);

    // body
    form.add(new Label("messageLabel", new ResourceModel("message.message")));
    final TextArea<String> messageField =
        new TextArea<String>("messageField", new PropertyModel<String>(newMessage, "message"));
    messageField.setMarkupId("messagebodyinput");
    messageField.setOutputMarkupId(true);
    messageField.setRequired(true);
    messageField.add(new RecipientEventBehavior("onfocus"));
    form.add(messageField);

    // send button
    IndicatingAjaxButton sendButton =
        new IndicatingAjaxButton("sendButton", form) {
          private static final long serialVersionUID = 1L;

          protected void onSubmit(AjaxRequestTarget target, Form form) {

            // get the backing model
            NewMessageModel newMessage = (NewMessageModel) form.getModelObject();

            // generate the thread id
            String threadId = ProfileUtils.generateUuid();

            // save it, it will be abstracted into its proper parts and email notifications sent
            if (messagingLogic.sendNewMessage(
                newMessage.getTo(),
                newMessage.getFrom(),
                threadId,
                newMessage.getSubject(),
                newMessage.getMessage())) {

              // post event
              sakaiProxy.postEvent(
                  ProfileConstants.EVENT_MESSAGE_SENT, "/profile/" + newMessage.getTo(), true);

              // success
              formFeedback.setDefaultModel(new ResourceModel("success.message.send.ok"));
              formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));

              // target.appendJavascript("$('#" + form.getMarkupId() + "').slideUp();");
              target.appendJavaScript("setMainFrameHeight(window.name);");

              // PRFL-797 all fields when successful, to prevent multiple messages.
              // User can just click Compose message again to get a new form
              this.setEnabled(false);
              autocompleteField.setEnabled(false);
              subjectField.setEnabled(false);
              messageField.setEnabled(false);
              target.add(this);
              target.add(autocompleteField);
              target.add(subjectField);
              target.add(messageField);

            } else {
              // error
              formFeedback.setDefaultModel(new ResourceModel("error.message.send.failed"));
              formFeedback.add(
                  new AttributeModifier("class", true, new Model<String>("alertMessage")));
            }

            formFeedback.setVisible(true);
            target.add(formFeedback);
          }

          protected void onError(AjaxRequestTarget target, Form form) {

            // check which item didn't validate and update the feedback model
            if (!toField.isValid()) {
              formFeedback.setDefaultModel(new ResourceModel("error.message.required.to"));
            }
            if (!messageField.isValid()) {
              formFeedback.setDefaultModel(new ResourceModel("error.message.required.body"));
            }
            formFeedback.add(
                new AttributeModifier("class", true, new Model<String>("alertMessage")));

            target.add(formFeedback);
          }
        };
    form.add(sendButton);
    sendButton.setModel(new ResourceModel("button.message.send"));

    add(form);
  }
  private void init() {
    feedback.setOutputMarkupId(true);
    add(feedback);
    CompoundPropertyModel model = new CompoundPropertyModel(new Adherent());
    setModel(model);

    add(new RequiredTextField<String>("nom").add(new FocusOnLoadBehavior()));
    add(new RequiredTextField<String>("prenom"));
    add(
        new RequiredTextField<String>("numeroLicense", String.class)
            .add(new PatternValidator("\\d{6}")));

    // numéro de téléphone au bon format (10 caractères numériques)
    RequiredTextField<String> telephone = new RequiredTextField<String>("telephone", String.class);
    telephone.add(ExactLengthValidator.exactLength(10));
    telephone.add(new PatternValidator("\\d{10}"));
    add(telephone);

    add(new RequiredTextField<String>("mail").add(EmailAddressValidator.getInstance()));

    // Ajout de la liste des niveaux
    List<String> niveaux = new ArrayList<String>();
    for (NiveauAutonomie n : NiveauAutonomie.values()) {
      niveaux.add(n.toString());
    }
    add(new DropDownChoice("niveau", niveaux));

    // Ajout de la liste des aptitudes
    List<String> aptitudes = new ArrayList<String>();
    for (Aptitude apt : Aptitude.values()) {
      aptitudes.add(apt.name());
    }
    add(new DropDownChoice("aptitude", aptitudes));

    // Ajout de la liste des niveaux d'encadrement
    List<String> encadrement = new ArrayList<String>();
    for (Adherent.Encadrement e : Adherent.Encadrement.values()) {
      encadrement.add(e.toString());
    }
    add(new DropDownChoice("encadrement", encadrement));

    // Ajout de la checkbox pilote
    add(new CheckBox("pilote", model.bind("pilote")));

    // Ajout des roles
    List<String> roles =
        Arrays.asList(new String[] {"ADMIN", "USER", "SECRETARIAT", "DP", "ENCADRANT"});
    add(new ListMultipleChoice<String>("roles", roles));

    // Ajout du champs date du certificat medical
    DateTextField dateCMTextFiled =
        new DateTextField(
            "dateCM", new PropertyModel<Date>(model, "dateCM"), new StyleDateConverter("S-", true));
    dateCMTextFiled.setRequired(true);
    add(dateCMTextFiled);
    dateCMTextFiled.add(new DatePicker());

    Date dateDuJour = new Date();
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(dateDuJour);
    int anneeCourante = gc.get(Calendar.YEAR);
    int nextAnnee = anneeCourante + 1;

    List<Integer> annees = new ArrayList<Integer>();
    annees.add(new Integer(anneeCourante));
    annees.add(new Integer(nextAnnee));

    DropDownChoice<Integer> listAnnee = new DropDownChoice<Integer>("anneeCotisation", annees);
    listAnnee.setRequired(true);
    add(listAnnee);

    // Ajout de la checkbox TIV
    add(new CheckBox("tiv", model.bind("tiv")));
    // commentaire
    TextArea<String> textareaInput = new TextArea<String>("commentaire");
    textareaInput.add(ExactLengthValidator.maximumLength(45));
    add(textareaInput);

    ContactPanel cuPanel = new ContactPanel("cuPanel", model);
    add(cuPanel);

    add(
        new AjaxButton("validAdherent") {
          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            Adherent adherent = (Adherent) form.getModelObject();
            try {

              ResaSession.get().getAdherentService().creerAdherent(adherent);

              setResponsePage(AccueilPage.class);
            } catch (TechnicalException e) {
              e.printStackTrace();
              error(e.getKey());
            }
          }
          // L'implémentation de cette méthode est nécessaire pour voir
          // les messages d'erreur dans le feedBackPanel

          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            target.addComponent(feedback);
          }
        });

    add(
        new Link("cancel") {
          @Override
          public void onClick() {
            setResponsePage(AccueilPage.class);
          }
        });
  }
  private void build() {

    feedbackPanel = new FeedbackPanel("feedback");
    add(feedbackPanel);

    form = new Form("questionForm");
    form.setOutputMarkupId(true);

    questionTitleField = new TextField("questionTitleField", new Model(""));
    questionTitleField.setRequired(true);
    questionTitleField.add(new FocusOnLoadBehavior());
    form.add(questionTitleField);

    if (question.getType().equals(Question.QuestionType.ALTER)) {
      form.add(new Label("promptHelpText", "(Refer to the alter as $$)"));
    } else if (question.getType().equals(Question.QuestionType.ALTER_PAIR)) {
      form.add(new Label("promptHelpText", "(Refer to the alters as $$1 and $$2)"));
    } else {
      form.add(new Label("promptHelpText", ""));
    }

    numericLimitsPanel = new NumericLimitsPanel("numericLimitsPanel", question);
    form.add(numericLimitsPanel);
    numericLimitsPanel.setVisible(false);

    multipleSelectionLimitsPanel = new MultipleSelectionLimitsPanel("multipleSelectionLimitsPanel");
    form.add(multipleSelectionLimitsPanel);
    multipleSelectionLimitsPanel.setVisible(false);

    timeUnitsPanel = new TimeUnitsPanel("timeUnitsPanel", question);
    form.add(timeUnitsPanel);
    timeUnitsPanel.setVisible(false);

    listLimitsPanel = new ListLimitsPanel("listLimitsPanel", question);
    form.add(listLimitsPanel);
    listLimitsPanel.setVisible(question.getAskingStyleList());

    questionPromptField = new TextArea("questionPromptField", new Model(""));
    questionPromptField.setRequired(true);
    form.add(questionPromptField);

    questionPrefaceField = new TextArea("questionPrefaceField", new Model(""));
    form.add(questionPrefaceField);

    questionCitationField = new TextArea("questionCitationField", new Model(""));
    form.add(questionCitationField);

    questionResponseTypeModel = new Model(Answer.AnswerType.TEXTUAL); // Could also leave this null.
    dropDownQuestionTypes =
        new DropDownChoice(
            "questionResponseTypeField",
            questionResponseTypeModel,
            Arrays.asList(Answer.AnswerType.values()));

    dropDownQuestionTypes.add(
        new AjaxFormComponentUpdatingBehavior("onchange") {
          protected void onUpdate(AjaxRequestTarget target) {
            onSelectionChanged(Integer.parseInt(dropDownQuestionTypes.getModelValue()));
            // target.addComponent(form);
            target.addComponent(numericLimitsPanel);
            target.addComponent(multipleSelectionLimitsPanel);
            target.addComponent(noneButtonLabel);
            target.addComponent(noneButtonCheckBox);
            target.addComponent(otherSpecifyLabel);
            target.addComponent(otherSpecifyCheckBox);
            target.addComponent(timeUnitsPanel);
            target.addComponent(listLimitsPanel);
          }
        });

    form.add(dropDownQuestionTypes);

    questionAnswerReasonModel = new Model(answerAlways);
    List<Object> answerChoices = new ArrayList<Object>();
    answerChoices.add(answerAlways);
    for (Expression expression : Expressions.forStudy(question.getStudyId())) {
      answerChoices.add(expression);
    }
    form.add(
        new DropDownChoice("questionAnswerReasonField", questionAnswerReasonModel, answerChoices));

    Label askingStyleListLabel = new Label("askingStyleListLabel", "Ask with list of alters:");
    askingStyleModel = new Model();
    askingStyleModel.setObject(Boolean.FALSE);
    AjaxCheckBox askingStyleListField =
        new AjaxCheckBox("askingStyleListField", askingStyleModel) {
          protected void onUpdate(AjaxRequestTarget target) {
            Boolean listLimitsVisible = false;

            if (questionResponseTypeModel.getObject().equals(Answer.AnswerType.MULTIPLE_SELECTION)
                || questionResponseTypeModel.getObject().equals(Answer.AnswerType.SELECTION))
              listLimitsVisible = (Boolean) askingStyleModel.getObject();

            listLimitsPanel.setVisible(listLimitsVisible);
            target.addComponent(form);
          }
        };
    askingStyleListLabel.setOutputMarkupId(true);
    askingStyleListLabel.setOutputMarkupPlaceholderTag(true);
    askingStyleListField.setOutputMarkupId(true);
    askingStyleListField.setOutputMarkupPlaceholderTag(true);
    form.add(askingStyleListLabel);
    form.add(askingStyleListField);
    if (question.getType().equals(Question.QuestionType.EGO)
        || question.getType().equals(Question.QuestionType.EGO_ID)) {
      askingStyleListLabel.setVisible(false);
      askingStyleListField.setVisible(false);
    }

    otherSpecifyLabel = new Label("otherSpecifyLabel", "Other/Specify Type Question?: ");
    otherSpecifyModel = new Model();
    otherSpecifyModel.setObject(Boolean.FALSE);
    otherSpecifyCheckBox = new CheckBox("otherSpecifyField", otherSpecifyModel);
    form.add(otherSpecifyLabel);
    form.add(otherSpecifyCheckBox);
    otherSpecifyLabel.setOutputMarkupId(true);
    otherSpecifyCheckBox.setOutputMarkupId(true);
    otherSpecifyLabel.setOutputMarkupPlaceholderTag(true);
    otherSpecifyCheckBox.setOutputMarkupPlaceholderTag(true);
    noneButtonLabel = new Label("noneButtonLabel", "NONE Button?: ");
    noneButtonModel = new Model();
    noneButtonModel.setObject(Boolean.FALSE);
    noneButtonCheckBox = new CheckBox("noneButtonField", noneButtonModel);
    form.add(noneButtonLabel);
    form.add(noneButtonCheckBox);
    noneButtonLabel.setOutputMarkupId(true);
    noneButtonCheckBox.setOutputMarkupId(true);
    noneButtonLabel.setOutputMarkupPlaceholderTag(true);
    noneButtonCheckBox.setOutputMarkupPlaceholderTag(true);
    noneButtonLabel.setVisible(false);
    noneButtonCheckBox.setVisible(false);

    // questionUseIfField = new TextField("questionUseIfField", new Model(""));
    // form.add(questionUseIfField);

    form.add(
        new AjaxFallbackButton("submitQuestion", form) {
          @Override
          public void onSubmit(AjaxRequestTarget target, Form form) {
            insertFormFieldsIntoQuestion(question);
            if (question.getId() == null) {
              List<Question> questions =
                  Questions.getQuestionsForStudy(question.getStudyId(), question.getType());
              questions.add(question);
              for (Integer i = 0; i < questions.size(); i++) {
                questions.get(i).setOrdering(i);
                DB.save(questions.get(i));
              }
            } else {
              DB.save(question);
            }
            form.setVisible(false);
            target.addComponent(parentThatNeedsUpdating);
            target.addComponent(form);
          }
        });
    add(form);

    setFormFieldsFromQuestion(question);
  }
Beispiel #21
0
  /**
   * Constructor that is invoked when page is invoked without a session.
   *
   * @param parameters Page parameters
   */
  public JavascriptPage(final PageParameters parameters) {
    super("Javascript binding");

    // Container to insert the wiQuery javascript binding
    Form<String> jsForm = new Form<String>("jsForm");
    add(jsForm);

    feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    jsForm.add(feedback);

    StringBuffer exampleJavaCode = new StringBuffer();
    exampleJavaCode.append("Options options = new Options();");
    exampleJavaCode.append("\n");
    exampleJavaCode.append("options.put(\"autoOpen\", false);");
    exampleJavaCode.append("\n");
    exampleJavaCode.append("\n");
    exampleJavaCode.append(
        "return new JsQuery(component).$().chain(\"dialog\", \"open\", options.getJavaScriptOptions());");

    binding = new Model<String>(exampleJavaCode.toString());
    TextArea<String> jsCode = new TextArea<String>("jsCode", binding);
    jsCode.add(new StringValidator.MaximumLengthValidator(200));
    jsForm.add(jsCode);

    AjaxSubmitLink jsSubmit =
        new AjaxSubmitLink("jsSubmit") {
          private static final long serialVersionUID = 1L;

          /* (non-Javadoc)
           * @see org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink#getAjaxCallDecorator()
           */
          @Override
          protected IAjaxCallDecorator getAjaxCallDecorator() {
            AjaxPreprocessingCallDecorator pre =
                new AjaxPreprocessingCallDecorator(null) {
                  private static final long serialVersionUID = 1L;

                  /* (non-Javadoc)
                   * @see org.apache.wicket.ajax.calldecorator.AjaxPreprocessingCallDecorator#decorateScript(java.lang.CharSequence)
                   */
                  @Override
                  public CharSequence decorateScript(CharSequence script) {
                    return "this.disabled=true; this.value='Generating';" + script;
                  }
                };

            AjaxPostprocessingCallDecorator post =
                new AjaxPostprocessingCallDecorator(pre) {
                  private static final long serialVersionUID = 1L;

                  /* (non-Javadoc)
                   * @see org.apache.wicket.ajax.calldecorator.AjaxPostprocessingCallDecorator#postDecorateOnSuccessScript(java.lang.CharSequence)
                   */
                  @Override
                  public CharSequence postDecorateOnSuccessScript(CharSequence script) {
                    return script + "this.disabled=false; this.value='Generate';";
                  }
                };
            return post;
          }

          /* (non-Javadoc)
           * @see org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink#onError(org.apache.wicket.ajax.AjaxRequestTarget, org.apache.wicket.markup.html.form.Form)
           */
          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            super.onError(target, form);

            target.addComponent(feedback);
          }

          /* (non-Javadoc)
           * @see org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink#onSubmit(org.apache.wicket.ajax.AjaxRequestTarget, org.apache.wicket.markup.html.form.Form)
           */
          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            try {
              getSession().cleanupFeedbackMessages();

              StringBuffer groovyScript = new StringBuffer();
              groovyScript.append("import org.odlabs.wiquery.core.javascript.*;").append("\n");
              groovyScript
                  .append("import org.odlabs.wiquery.core.javascript.helper.*")
                  .append("\n");
              groovyScript.append("import org.odlabs.wiquery.ui.core.*;").append("\n");
              groovyScript.append("import org.odlabs.wiquery.core.options.*;").append("\n");
              groovyScript.append(binding.getObject());

              GroovyCodeSource codeSource =
                  new GroovyCodeSource(
                      groovyScript.toString(), "wiQueryScript", "/serverCodeBase/restrictedClient");

              GroovyShell groovyShell = ((WicketApplication) getApplication()).getGroovyShell();
              groovyShell.setVariable("component", jsGenerated);
              Object returnObject = groovyShell.evaluate(codeSource);

              if (returnObject instanceof JsStatement
                  || returnObject instanceof JsQuery
                  || returnObject instanceof JsScope) {

                String render = null;

                if (returnObject instanceof JsStatement) {
                  render = ((JsStatement) returnObject).render().toString();

                } else if (returnObject instanceof JsQuery) {
                  render = ((JsQuery) returnObject).getStatement().render().toString();

                } else {
                  render = ((JsScope) returnObject).render().toString();
                }

                jsGenerated.setDefaultModelObject(render);

              } else {
                error("The Java code must return a JsQuery or a JsStatement or a JsScope");
                jsGenerated.setDefaultModelObject("");
              }

            } catch (Exception e) {
              error("Generation error / Bad syntax");
              jsGenerated.setDefaultModelObject("");
              e.printStackTrace();
            }

            target.addComponent(feedback);
            target.addComponent(jsGenerated);
          }
        };
    jsForm.add(jsSubmit);

    // Container to display generatd javascript
    jsGenerated = new Label("jsGenerated", new Model<String>());
    jsGenerated.setOutputMarkupPlaceholderTag(true);
    add(jsGenerated);
  }
Beispiel #22
0
    public TemplateForm(String id, final String section, boolean custom, UserData u) {
      super(id);
      this.user = u;
      this.section = section;
      final com.rectang.xsm.site.Site site = user.getSite();

      Button create =
          new Button("create") {
            public void onSubmit() {
              InputStream in = null;
              OutputStream out = null;
              try {
                in = getDefault(section, user.getSite());
                out = new FileOutputStream(getCustomFile(section));
                IOUtil.copyStream(in, out);

                if (section.equals("layout")) {
                  site.setLayout("custom");
                  site.save();
                } else if (section.equals("style")) {
                  site.setStylesheet("custom");
                  site.save();
                }

                // Here we need to redirect back to this page to refresh the models - not sure
                // why...
                setResponsePage(EditTemplate.class, getPageParameters());
              } catch (IOException e) {
                error("Unable to create custom copy of template " + section);
              } finally {
                if (in != null) {
                  IOUtil.close(in);
                }
                if (out != null) {
                  IOUtil.close(out);
                }
              }
            }
          };
      create.setDefaultFormProcessing(false);
      add(create);

      Button save = new Button("save");
      add(save);

      Button revert = new Button("revert");
      add(revert);

      Button delete =
          new Button("delete") {
            public void onSubmit() {
              if (getCustomFile(section).delete()) {
                if (section.equals("layout")) {
                  site.setLayout("menu-left");
                  site.save();
                } else if (section.equals("style")) {
                  site.setStylesheet("grey");
                  site.getPublishedDoc("style.css").delete();
                  site.save();
                }

                if (section.equals("template")) {
                  site.publish(user);
                } else {
                  site.publishTheme();
                }
                // Here we need to redirect back to this page to refresh the models - not sure
                // why...
                setResponsePage(EditTemplate.class, getPageParameters());
              } else {
                error("Unable to delete custom template " + section);
              }
            }
          };
      delete.setDefaultFormProcessing(false);
      add(delete);

      if (custom) {
        add(new TextArea("customise", new StringFileModel(getCustomFile(section))));

        create.setVisible(false);
      } else {
        StringBuffer content = new StringBuffer();
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new InputStreamReader(getDefault(section, site)));

          String line = reader.readLine();
          while (line != null) {
            content.append(line);
            content.append('\n');

            line = reader.readLine();
          }
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          if (reader != null) {
            IOUtil.close(reader);
          }
        }

        TextArea area = new TextArea("customise", new Model(content.toString()));

        area.setEnabled(false);
        add(area);

        save.setVisible(false);
        revert.setVisible(false);
        delete.setVisible(false);
      }

      BookmarkablePageLink back;
      back = new BookmarkablePageLink("back", Theme.class);
      back.add(new Label("back-label", "Back to Theme page"));
      add(back);
    }
  /** @param ruleId */
  private void addNewComponentForm(final Integer ruleId) {
    IModel<DNRuleComponent> formModel =
        new CompoundPropertyModel<DNRuleComponent>(new DNRuleComponent());

    Form<DNRuleComponent> form =
        new Form<DNRuleComponent>("newDNRuleComponentForm", formModel) {
          private static final long serialVersionUID = 1L;

          @Override
          protected void onSubmit() {
            DNRuleComponent dnRuleComponent = this.getModelObject();
            dnRuleComponent.setRuleId(ruleId);

            try {
              dnRuleComponentDao.save(dnRuleComponent);
            } catch (DaoException ex) {
              logger.error(ex.getMessage(), ex);
              getSession().error(ex.getMessage());
              return;
            } catch (Exception ex) {
              logger.error(ex.getMessage(), ex);
              getSession()
                  .error("The component could not be registered due to an unexpected error.");

              return;
            }

            getSession().info("The component was successfuly registered.");
            setResponsePage(new DNRuleDetailPage(ruleId));
          }
        };

    final TextArea<String> modification = new TextArea<String>("modification");

    ChoiceRenderer<DNRuleComponentType> renderer =
        new ChoiceRenderer<DNRuleComponentType>("label", "id");
    LoadableDetachableModel<List<DNRuleComponentType>> choices =
        new LoadableDetachableModel<List<DNRuleComponentType>>() {
          private static final long serialVersionUID = 1L;

          @Override
          protected List<DNRuleComponentType> load() {
            return dnRuleComponentTypeDao.loadAll();
          }
        };
    DropDownChoice<DNRuleComponentType> type =
        new DropDownChoice<DNRuleComponentType>("type", choices, renderer) {
          private static final long serialVersionUID = 1L;

          @Override
          public void onSelectionChanged(DNRuleComponentType newType) {
            String hint;

            if (newType.getLabel().equals("INSERT")) {

              hint = insertHint;

            } else if (newType.getLabel().equals("DELETE")) {

              hint = deleteHint;

            } else {

              hint = modifyHint;
            }

            modification.add(new AttributeModifier("placeholder", hint));
          }

          @Override
          protected boolean wantOnSelectionChangedNotifications() {
            return true;
          }

          @Override
          protected CharSequence getDefaultChoice(String selectedValue) {
            return !isNullValid() && !getChoices().isEmpty()
                ? ""
                : super.getDefaultChoice(selectedValue);
          }
        };
    type.setNullValid(false);
    type.setRequired(true);
    form.add(type);

    modification.setRequired(true);
    modification.add(
        new DNComponentValidator(
            ConfigLoader.getConfig().getBackendGroup().getDirtyDBJDBCConnectionCredentials(),
            type));
    modification.add(new AttributeModifier("placeholder", insertHint));
    form.add(modification);

    form.add(createTextarea("description", false));

    add(form);
  }