@Override protected TextField<String> newTextField( String id, IModel<String> valueModel, final ImportableRemoteRepo rowObject) { TextField<String> textField = super.newTextField(id, valueModel, rowObject); textField.setLabel(Model.of("Key")); textField.setOutputMarkupId(true); textField.setRequired(true); textField.add(new NameValidator("Invalid repository key '%s'.")); textField.add(new XsdNCNameValidator("Invalid repository key '%s'.")); textField.add( new AjaxFormComponentUpdatingBehavior("onkeyup") { @Override protected void onUpdate(AjaxRequestTarget target) { validateRepoKey(rowObject); // On each update, refresh import button to customize the warning messages of the call // decorator target.add(importButton); } @Override protected void onError(AjaxRequestTarget target, RuntimeException e) { super.onError(target, e); AjaxUtils.refreshFeedback(); } @Override protected IAjaxCallDecorator getAjaxCallDecorator() { return new NoAjaxIndicatorDecorator(); } }); return textField; }
/* * (non-Javadoc) * * @see au.org.theark.core.web.form.AbstractDetailForm#attachValidators() */ @Override protected void attachValidators() { customFieldGroupTxtFld .setRequired(true) .setLabel( new StringResourceModel( "customFieldGroup.name", this, new Model<String>("Custom Field Group Name"))); customFieldGroupTxtFld.add(StringValidator.maximumLength(1000)); }
private void addDetailFields() { Label id = new Label("id"); add(id); customer = new TextField("customer"); add(customer); customer.setRequired(true); TextField attr_g = new TextField("attr_g"); add(attr_g); attr_g.setRequired(false); TextField attr_h = new TextField("attr_h"); add(attr_h); attr_h.setRequired(false); TextField attr_i = new TextField("attr_i"); add(attr_i); attr_i.setRequired(false); }
/** @see Form#Form(String) */ public UploadForm(String id) { super(id); // multipart always needed for uploads setMultiPart(true); // input field for identifier text identifier = new TextField<String>("identifier", new Model<String>()); // pattern validator identifier.add(new PatternValidator("[A-Za-z0-9 _\\-]+")); // validator that checks if the project name is already taken identifier.add( new IValidator<String>() { private static final long serialVersionUID = 275885544279441469L; @Override public void validate(IValidatable<String> validatable) { String name = validatable.getValue(); for (String project : projects.getResources()) { // ignore case to avoid confusion if (name.equalsIgnoreCase(project)) { validatable.error(new ValidationError().setMessage("Identifier already in use")); break; } } } }); FieldMessage identifierMessage = new FieldMessage( "identifierMessage", new Model<String>("Unique identifier for the project"), identifier); identifier.add(new FieldValidatingBehavior("onblur", identifierMessage)); identifier.setOutputMarkupId(true); identifier.setRequired(true); // identifier.add(new DefaultFocus()); XXX not working well with ajax add(identifier); add(identifierMessage); // Add one file input field add(file = new FileUploadField("file")); add(new FeedbackPanel("feedback")); addAllowedContentType("application/zip"); addAllowedContentType("application/x-zip"); addAllowedContentType("application/x-zip-compressed"); addAllowedContentType("application/octet-stream"); // setCustomTypeErrorMessage("Only ZIP archives are supported for upload"); setMaxSize(Bytes.megabytes(20)); }
public SpatialFilePanel(String id) { super(id); add(dialog = new GeoServerDialog("dialog")); Form form = new Form("form", new CompoundPropertyModel(this)); add(form); fileField = new TextField("file"); fileField.setRequired(true); fileField.setOutputMarkupId(true); form.add(fileField); form.add(chooserButton(form)); }
public SearchBookForm(String id, String action) { super(id); this.action = action; setDefaultModel(new CompoundPropertyModel<SearchBookForm>(this)); TextField<String> title = new TextField<>("title"); title.setLabel(Model.of("Title")); add(title); TextField<String> author = new TextField<>("author"); author.setLabel(Model.of("Author")); author.setRequired(false); add(author); add(new Button("searchBookSubmit")); }
public PageInscription(PageParameters pp) { super(pp); setStatelessHint(true); final TextField<String> field = new TextField<String>("email", new PropertyModel<String>(this, "email")); field.add(EmailAddressValidator.getInstance()); field.setRequired(true); StatelessForm<?> statelessForm = new StatelessForm("statelessform") { @Override protected void onSubmit() { serviceUser.log("Création user pour : " + field.getDefaultModelObject()); info("Un email de validation vous a été envoyé."); } }; statelessForm.add(field); add(statelessForm); add(new FeedbackPanel("feedback")); }
/* * (non-Javadoc) * * @see au.org.theark.core.web.form.AbstractDetailForm#attachValidators() */ @Override protected void attachValidators() { areaCodeTxtFld.add(StringValidator.maximumLength(10)); phoneTypeChoice .setRequired(true) .setLabel( (new StringResourceModel( "phone.phoneType.required", this, new Model<String>("Phone Type")))); phoneNumberTxtFld .setRequired(true) .setLabel( (new StringResourceModel( "phone.phoneNumber.required", this, new Model<String>("Phone Number")))); phoneStatusChoice .setRequired(true) .setLabel( (new StringResourceModel( "phone.phoneStatus.required", this, new Model<String>("Phone Status")))); phoneNumberTxtFld.add(StringValidator.maximumLength(20)); dateReceivedDp .add(DateValidator.maximum(new Date())) .setLabel(new StringResourceModel("phone.dateReceived.DateValidator.maximum", this, null)); }
/** * @param id * @param paramsMap * @param paramName * @param paramLabelModel * @param required * @param validators any extra validator that should be added to the input field, or {@code null} */ public FileParamPanel( final String id, final IModel paramValue, final IModel paramLabelModel, final boolean required, IValidator... validators) { // make the value of the text field the model of this panel, for easy value retrieval super(id, paramValue); // add the dialog for the file chooser add(dialog = new ModalWindow("dialog")); // the label String requiredMark = required ? " *" : ""; Label label = new Label("paramName", paramLabelModel.getObject() + requiredMark); add(label); // the text field, with a decorator for validations textField = new TextField("paramValue", new FileModel(paramValue)); textField.setRequired(required); textField.setOutputMarkupId(true); // set the label to be the paramLabelModel otherwise a validation error would look like // "Parameter 'paramValue' is required" textField.setLabel(paramLabelModel); if (validators != null) { for (IValidator validator : validators) { textField.add(validator); } } FormComponentFeedbackBorder feedback = new FormComponentFeedbackBorder("border"); feedback.add(textField); feedback.add(chooserButton((String) paramLabelModel.getObject())); add(feedback); }
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); }
public CoverageViewAbstractPage( String workspaceName, String storeName, String coverageName, CoverageInfo coverageInfo) throws IOException { storeId = getCatalog().getStoreByName(workspaceName, storeName, CoverageStoreInfo.class).getId(); Catalog catalog = getCatalog(); CoverageStoreInfo store = catalog.getStore(storeId, CoverageStoreInfo.class); GridCoverage2DReader reader = (GridCoverage2DReader) catalog.getResourcePool().getGridCoverageReader(store, null); String[] coverageNames = reader.getGridCoverageNames(); if (availableCoverages == null) { availableCoverages = new ArrayList<String>(); } for (String coverage : coverageNames) { ImageLayout layout = reader.getImageLayout(coverage); SampleModel sampleModel = layout.getSampleModel(null); final int numBands = sampleModel.getNumBands(); if (numBands == 1) { // simple syntax for simple case availableCoverages.add(coverage); } else { for (int i = 0; i < numBands; i++) { availableCoverages.add(coverage + CoverageView.BAND_SEPARATOR + i); } } } Collections.sort(availableCoverages); name = COVERAGE_VIEW_NAME; if (coverageName != null) { newCoverage = false; // grab the coverage view coverageViewInfo = coverageInfo != null ? coverageInfo : catalog.getResourceByStore(store, coverageName, CoverageInfo.class); CoverageView coverageView = coverageViewInfo.getMetadata().get(CoverageView.COVERAGE_VIEW, CoverageView.class); // the type can be still not saved if (coverageViewInfo != null) { coverageInfoId = coverageViewInfo.getId(); } if (coverageView == null) { throw new IllegalArgumentException( "The specified coverage does not have a coverage view attached to it"); } outputBands = new ArrayList<CoverageBand>(coverageView.getCoverageBands()); name = coverageView.getName(); } else { outputBands = new ArrayList<CoverageBand>(); newCoverage = true; coverageViewInfo = null; } selectedCoverages = new ArrayList<String>(availableCoverages); // build the form and the text area Form<CoverageViewAbstractPage> form = new Form<>("form", new CompoundPropertyModel<>(this)); add(form); final TextField<String> nameField = new TextField<>("name"); nameField.setRequired(true); nameField.add(new CoverageViewNameValidator()); form.add(nameField); coverageEditor = new CoverageViewEditor( "coverages", new PropertyModel<>(this, "selectedCoverages"), new PropertyModel<>(this, "outputBands"), availableCoverages); form.add(coverageEditor); // save and cancel at the bottom of the page form.add( new SubmitLink("save") { @Override public void onSubmit() { onSave(); } }); form.add( new Link<Void>("cancel") { @Override public void onClick() { onCancel(); } }); }
@SuppressWarnings("serial") public IncluirUsuarioPage(final PageParameters parameters) { super(parameters, "Usuário", "Incluir usuário"); @SuppressWarnings("rawtypes") Form form = new Form("form"); add(form); form.add(new FeedbackPanel("mensagem")); TextField<String> textFieldNome = new TextField<String>("nome", new PropertyModel<String>(this, "usuario.nome")); textFieldNome.setRequired(true); form.add(textFieldNome); TextField<String> textFieldLogin = new TextField<String>("login", new PropertyModel<String>(this, "usuario.login")); textFieldLogin.setRequired(true); form.add(textFieldLogin); form.add(new PasswordTextField("senha", new PropertyModel<String>(this, "usuario.senha"))); form.add( new PasswordTextField( "confirmarSenha", new PropertyModel<String>(this, "senhaConfirmada"))); List<Permissao> permissoes = (List<Permissao>) new PermissaoBO().getListaTodasPermissoes(); @SuppressWarnings("rawtypes") IChoiceRenderer renderer = new ChoiceRenderer("descricao", "codigo"); @SuppressWarnings({"rawtypes", "unchecked"}) final Palette palette = new Palette( "palette", new ListModel<Permissao>(new ArrayList<Permissao>()), new CollectionModel<Permissao>(permissoes), renderer, 10, true); form.add(palette); form.add( new Button("btnSalvar") { @Override public void onSubmit() { // Verifica se o login já foi cadastrado UsuarioBO usuarioBO = new UsuarioBO(); if (isSenhaValida()) { usuario.setLogin(usuario.getLogin().toLowerCase()); if (!usuarioBO.isLoginCadastrado(usuario)) { @SuppressWarnings("unchecked") ListModel<Permissao> modelPermissao = (ListModel<Permissao>) palette.getDefaultModel(); usuario.setListaPermissao(modelPermissao.getObject()); usuarioBO.inserir(usuario); setResponsePage(new ListarUsuarioPage(usuario.getId())); } else { error("Login já cadastrado."); } } else { error("A Senha confirmada é diferente da Senha informada."); } } }); Button btnVoltar = new Button("btnVoltar") { @Override public void onSubmit() { setResponsePage(ListarUsuarioPage.class); } }; btnVoltar.setDefaultFormProcessing(false); form.add(btnVoltar); }
public OldNewReleasePage(PageParameters pp, String info) { super(pp, info); setActiveMenu(Menu.RELEASES); add(new FeedbackPanel("feedbackMessage")); Form newReleaseForm = new Form("form-newrelease", new CompoundPropertyModel(newRelease)) { @Override protected void onSubmit() { System.out.println("Submit: " + newRelease); PVTDataAccessObject dao = PVTApplication.getDAO(); dao.getPvtModel().addRelease(newRelease); dao.persist(); setResponsePage(new ReleasesPage(pp, "Release: " + newRelease.getName() + " Created.")); } }; List<String> productNames = new ArrayList<>(); for (Product p : PVTApplication.getDAO().getPvtModel().getProducts()) { productNames.add(p.getName()); } DropDownChoice<String> productDropDownChoice = new DropDownChoice<String>( "productName", Model.ofList(productNames), new ChoiceRenderer<String>("toString", "toString") {}) { @Override public boolean isNullValid() { return true; } }; productDropDownChoice.setRequired(true); newReleaseForm.add(productDropDownChoice); TextField<String> nameTextField = new TextField<String>("name"); nameTextField.setRequired(true); newReleaseForm.add(nameTextField); newReleaseForm.add(new TextArea<String>("distributions")); newReleaseForm.add(new TextArea<String>("description")); newReleaseForm.add( new CheckBoxMultipleChoice<String>( "jobs", Model.ofList( Arrays.asList("ZipDiff", "Version convention", "JDK version compatible")))); newReleaseForm.add( new IFormValidator() { public FormComponent<?>[] getDependentFormComponents() { return new FormComponent[] {nameTextField, productDropDownChoice}; } public void validate(Form<?> form) { PVTDataAccessObject dao = PVTApplication.getDAO(); boolean existed = false; for (Release rel : dao.getPvtModel().getReleases()) { if (rel.getName().equalsIgnoreCase(nameTextField.getInput()) && rel.getProductId().equalsIgnoreCase(productDropDownChoice.getInput())) { existed = true; break; } } if (existed) { ValidationError error = new ValidationError(); error.setMessage( "The Release " + productDropDownChoice.getInput() + "-" + nameTextField.getInput() + " is already existed"); nameTextField.error(error); } } }); add(newReleaseForm); }
@Override protected void onInitialize() { super.onInitialize(); add(new FeedbackPanel("feedback")); final Administrator newAdmin = new Administrator(); newAdmin.setAccessLevel("passenger"); Form<TripList> form = new Form<>("administrator-registration-form"); add(form); TextField<String> loginField = new TextField<String>("login", new PropertyModel<String>(newAdmin, "login")); loginField.setRequired(true); loginField.add(StringValidator.maximumLength(50)); form.add(loginField); // можно добавить второе поле для проверки корректности ввода PasswordTextField passwordField = new PasswordTextField("password", new PropertyModel<String>(newAdmin, "password")); passwordField.setRequired(true); passwordField.add(StringValidator.maximumLength(50)); form.add(passwordField); TextField<String> firstNameField = new TextField<String>("first-name", new PropertyModel<String>(newAdmin, "firstName")); firstNameField.setRequired(true); firstNameField.add(StringValidator.maximumLength(50)); form.add(firstNameField); TextField<String> lastNameField = new TextField<String>("last-name", new PropertyModel<String>(newAdmin, "lastName")); lastNameField.setRequired(true); lastNameField.add(StringValidator.maximumLength(50)); form.add(lastNameField); TextField<String> emailField = new TextField<String>("email", new PropertyModel<String>(newAdmin, "email")); emailField.setRequired(true); emailField.add(StringValidator.maximumLength(50)); form.add(emailField); form.add( new SubmitLink("submit-button") { @Override public void onSubmit() { // TODO - correct // if (aService.getByLogin(newAdmin.getLogin()) != null) { // warn("such login already exists"); // } // if (aService.getByLogin(newAdmin.getLogin()) != null) { // warn("user with such email already exists"); // } // // if (aService.getByLogin(newAdmin.getLogin()) == null // && aService.getByLogin(newAdmin.getLogin()) == null) { aService.register(newAdmin); setResponsePage(new HomePage()); // } } }); }
public ProductUpdatePage(PageParameters params) { final Long productId = params.get(PARAM_PRODUCT_ID).toLongObject(); ProductDto product = null; try { product = PriceComparatorApplication.getApi().getProduct(productId); } catch (PriceComparatorBusinesException e) { // TODO e.printStackTrace(); } updateDto = new ProductUpdateDto(); updateDto.setId(productId); updateDto.setName(product.getName()); updateDto.setUnit(product.getUnit()); updateDto.setCountOfUnit(product.getCountOfUnit()); updateDto.setCountOfItemInOnePackage(product.getCountOfItemInOnePackage()); add(new FeedbackPanel("feedback")); Form<Void> form = new Form<Void>("form") { @Override protected void onSubmit() { try { PriceComparatorApplication.getApi().updateProduct(updateDto); setResponsePage(ProductListPage.class); } catch (Exception e) { // TODO e.printStackTrace(); } } }; add(form); TextField<String> productName = new TextField<>( "productName", new PropertyModel<String>(updateDto, ProductUpdateDto.AT_NAME)); productName.setRequired(true); form.add(productName); RadioGroup<Unit> group = new RadioGroup<>("group", new PropertyModel<Unit>(updateDto, ProductUpdateDto.AT_UNIT)); form.add(group); Radio<Unit> kus = new Radio<>("kus", Model.of(Unit.KUS)); Radio<Unit> vaha = new Radio<>("vaha", Model.of(Unit.KILOGRAM)); Radio<Unit> objem = new Radio<>("objem", Model.of(Unit.LITER)); Radio<Unit> dlzka = new Radio<>("dlzka", Model.of(Unit.METER)); Radio<Unit> davka = new Radio<>("davka", Model.of(Unit.DAVKA)); group.add(kus, vaha, objem, dlzka, davka); TextField<BigDecimal> countOfUnit = new TextField<>( "countOfUnit", new PropertyModel<BigDecimal>(updateDto, ProductUpdateDto.AT_COUNT_OF_UNIT)); countOfUnit.setRequired(true); form.add(countOfUnit); TextField<Integer> countOfItemInOnePackage = new TextField<>( "countOfItemInOnePackage", new PropertyModel<Integer>( updateDto, ProductUpdateDto.AT_COUNT_OF_ITEM_IN_ONE_PACKAGE)); countOfItemInOnePackage.setRequired(true); form.add(countOfItemInOnePackage); }
@SuppressWarnings("serial") @Override protected void onInitialize() { super.onInitialize(); Double fieldRateValue = 100.0; Model<Double> rateValueModel = new Model<Double>(fieldRateValue); List<Rate> rates = new ArrayList<>(); List<Coefficient> coefficientsList = new ArrayList<>(); Map<String, Object> atributes = new HashMap<>(); atributes.put("hourseRacingId", hourseRacing.getId()); // initialization racingLine list of racingLine where // hourseRacingId=current horse racing id List<RacingLine> racingLineList = new ArrayList<>(racingLineService.getAll(atributes, "id", true)); int racingLineListSize = racingLineList.size(); // initialization rateLine list of all of rateLine List<RateLine> rateLineList = new ArrayList<>(rateLineService.getAll(null, "id", true)); int rateLineListSize = rateLineList.size(); List<CoefficientView> coefficientViewList = new ArrayList<>(); for (int i = 0; i < racingLineListSize; i++) { RacingLine racingline = racingLineList.get(i); CoefficientView coefficientView = new CoefficientView(); int racingLineId = racingline.getId(); coefficientView.participantName = participantService.getViewById(racingline.getParticipantId()).toStringShort(); for (int r = 0; r < rateLineListSize; r++) { int rateLineId = rateLineList.get(r).getId(); Map<String, Object> findingAtributes = new HashMap<>(); findingAtributes.put("rateLineId", rateLineId); findingAtributes.put("racingLineId", racingLineId); List<Coefficient> coefficients = coefficientService.getAll(findingAtributes, null, true); Coefficient coefficient; if (coefficients.size() != 0) { coefficient = coefficients.get(0); } else { coefficient = new Coefficient(); } PropertyModel<Double> propertyModel = new PropertyModel<>(coefficient, "value"); coefficientView.coefficients.add(coefficient.getId()); coefficientView.coefficientsModels.put(coefficient.getId(), propertyModel); } coefficientViewList.add(coefficientView); } add(new Label("sel-hourse-racing-title", hourseRacing.toString())); for (int i = 0; i < CoefficientEditPage.MAXQUANTITY; i++) { String title = "Empty"; if (i < rateLineListSize) { title = rateLineList.get(i).getTitle(); } add(new Label(String.format("title-%s", i), title)); } Form<Void> form = new Form<>("rate-form"); add(form); form.setOutputMarkupId(true); // Model<Double> rateValueModel = new Model<>(rateValueModel); TextField<Double> rateValueTextField = new TextField<Double>("rate-value", rateValueModel, Double.class); form.add(rateValueTextField.setRequired(true)); final Model<Double> model = new Model<Double>(0.0); final Label label = new Label("possible-winning-label", model); // label.setOutputMarkupId(true); form.add(label); // Model<Double> posWinModel=new Model(posWin); // Label posWinLabel = new Label("possible-winning-label", posWinModel); // posWinLabel.setOutputMarkupId(true); // form.add(posWinLabel); ListView<Rate> listView = new ListView<Rate>("rate-list", rates) { @Override protected void populateItem(ListItem<Rate> item) { final Rate rate = item.getModelObject(); item.add(new Label("rate-coefficient-label", rate.getCoefficientValue())); } }; form.add(listView); LinkForRole balanceLink = new LinkForRole("add-balance-link") { @Override public void onClick() { setResponsePage( new AddBalance( userService.getById( Session.get() .getMetaData(UserSession.USER_METADATA_KEY) .getUser() .getId()))); } }; add(balanceLink); form.add( new SubmitLink("submit-button") { @Override public void onSubmit() { if (UserSession.get().isSignedIn()) { int userId = Session.get().getMetaData(UserSession.USER_METADATA_KEY).getUser().getId(); double checkBalance = 0.0; for (Rate rate : rates) { checkBalance += rateValueModel.getObject(); } if (rates.size() == 0) { SelectCoefficient responsePage = new SelectCoefficient(hourseRacing); responsePage.warn(getString("page.selectCoefficient.no.rates")); setResponsePage(responsePage); } else { if (userService.getById(userId).getBalance() < checkBalance) { SelectCoefficient responsePage = new SelectCoefficient(hourseRacing); responsePage.warn(getString("page.selectCoefficient.insufficient.funds")); setResponsePage(responsePage); } else { for (Rate rate : rates) { rate.setUserId(userId); rate.setValue(rateValueModel.getObject()); LOGGER.info("Submit link. Inser or update {}", rate); rateService.doRate(rate); SelectCoefficient responsePage = new SelectCoefficient(hourseRacing); responsePage.info(getString("all.data.saved")); setResponsePage(responsePage); } } } } else { setResponsePage(LoginPage.class); } } }); add( new ListView<CoefficientView>("sel-coefficient-list", coefficientViewList) { @Override protected void populateItem(ListItem<CoefficientView> item) { final CoefficientView coefficientView = item.getModelObject(); item.add(new Label("participant", coefficientView.participantName)); int modelsSize = coefficientView.coefficientsModels.size(); for (int q = 0; q < CoefficientEditPage.MAXQUANTITY; q++) { String id = String.valueOf(q); if (q < modelsSize) { int key = coefficientView.coefficients.get(q); PropertyModel<Double> coefModel = coefficientView.coefficientsModels.get(key); Label coefValue = new Label("coef-value-" + id, coefModel); AjaxLink<Void> ajaxLink = new AjaxLink<Void>(id) { @Override public void onClick(AjaxRequestTarget target) { boolean isContains = false; for (int i = 0; i < rates.size(); i++) { if (rates.get(i).getCoefficientId() == key) { rates.remove(i); isContains = true; } } if (!isContains) { Rate rate = new Rate(); rate.setCoefficientValue(coefModel.getObject()); rate.setCoefficientId(key); rates.add(rate); add(AttributeModifier.replace("class", "button-red")); } else { add(AttributeModifier.replace("class", "button")); } model.setObject(getPosWin(rates, rateValueModel)); // target.add(label); rateValueModel.setObject(Double.valueOf(rateValueTextField.getValue())); target.add(form); target.add(this); } }; item.add(ajaxLink.add(coefValue)); if (coefModel.getObject() == 0) { ajaxLink.setVisible(false); } } else { Label coefValue = new Label("coef-value-" + q, new Model<Double>()); item.add( ((new AjaxLink<Void>(String.valueOf(q)) { @Override public void onClick(AjaxRequestTarget target) { System.out.println("rates.size()=" + rates.size()); for (int i = 0; i < rates.size(); i++) { if (rates.get(i).getCoefficientId() == 0) { rates.remove(i); } else { Rate rate = new Rate(); PropertyModel<Double> valueModel = coefficientView.coefficientsModels.get(index); rate.setCoefficientValue(valueModel.getObject()); rate.setCoefficientId(coefficientsList.get(i).getId()); rates.add(rate); } } getPosWin(rates, rateValueModel); target.add(form); } }) .add(coefValue)) .setVisible(false)); } } } }); add(new BookmarkablePageLink<Void>("sel-hourse-racing-page-link", HorseRacingPage.class)); }
protected void initUI(StyleInfo style) { IModel<StyleInfo> styleModel = new CompoundPropertyModel( style != null ? new StyleDetachableModel(style) : getCatalog().getFactory().createStyle()); styleForm = new Form("form", styleModel) { @Override protected void onSubmit() { super.onSubmit(); onStyleFormSubmit(); } }; styleForm.setMarkupId("mainForm"); add(styleForm); styleForm.add(nameTextField = new TextField("name")); nameTextField.setRequired(true); DropDownChoice<WorkspaceInfo> wsChoice = new DropDownChoice("workspace", new WorkspacesModel(), new WorkspaceChoiceRenderer()); wsChoice.setNullValid(true); if (!isAuthenticatedAsAdmin()) { wsChoice.setNullValid(false); wsChoice.setRequired(true); } styleForm.add(wsChoice); styleForm.add(editor = new CodeMirrorEditor("SLD", new PropertyModel(this, "rawSLD"))); // force the id otherwise this blasted thing won't be usable from other forms editor.setTextAreaMarkupId("editor"); editor.setOutputMarkupId(true); editor.setRequired(true); styleForm.add(editor); if (style != null) { try { setRawSLD(readFile(style)); } catch (IOException e) { // ouch, the style file is gone! Register a generic error message Session.get() .error(new ParamResourceModel("sldNotFound", this, style.getFilename()).getString()); } } // style copy functionality styles = new DropDownChoice( "existingStyles", new Model(), new StylesModel(), new StyleChoiceRenderer()); styles.setOutputMarkupId(true); styles.add( new AjaxFormComponentUpdatingBehavior("onchange") { @Override protected void onUpdate(AjaxRequestTarget target) { styles.validate(); copyLink.setEnabled(styles.getConvertedInput() != null); target.addComponent(copyLink); } }); styleForm.add(styles); copyLink = copyLink(); copyLink.setEnabled(false); styleForm.add(copyLink); uploadForm = uploadForm(styleForm); uploadForm.setMultiPart(true); uploadForm.setMaxSize(Bytes.megabytes(1)); uploadForm.setMarkupId("uploadForm"); add(uploadForm); uploadForm.add(fileUploadField = new FileUploadField("filename")); add(validateLink()); Link cancelLink = new Link("cancel") { @Override public void onClick() { setResponsePage(StylePage.class); } }; add(cancelLink); }
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); }
public UserDetailForm(final String id) { super(id); name = new TextField("name", new PropertyModel(properties, "name")); name.setRequired(true); name.setModelValue(user.getName()); add(name); // add(nameFeedback = new ComponentFeedbackPanel("nameFeedback", // name)); add(new Label("nameLabel", "Meno")); add(new FormComponentFeedbackBorder("border").add(name)); surname = new TextField("surname", new PropertyModel(properties, "surname")); surname.setRequired(true); surname.setModelValue(user.getSurname()); add(surname); // add(surnameFeedback = new ComponentFeedbackPanel("surnameFeedback", // surname)); add(new Label("surnameLabel", "Priezvisko")); email = new TextField("email", new PropertyModel(properties, "email")); email.setRequired(true); email.setModelValue(user.getEmail()); email.setEnabled(false); add(email); // add(addressFeedback = new ComponentFeedbackPanel("addressFeedback", // address)); add(new Label("emailLabel", "Email")); login = new TextField("login", new PropertyModel(properties, "login")); login.setRequired(true); login.setModelValue(user.getLogin()); login.setEnabled(false); add(login); // add(loginNameFeedback = new ComponentFeedbackPanel("loginNameFeedback", // loginName)); add(new Label("loginLabel", "Login")); // region= new TextField("region", new PropertyModel(properties, // "region")); // region.setRequired(false); // region.setModelValue(user.getRegion()); // add(region); // add(new Label("regionLabel","Region")); County mesto = new County(); town = new DropDownChoice("town", new PropertyModel(mesto, "name"), TOWN_LIST); town.setRequired(false); if (user.getTown() != null) mesto.setName(user.getTown().getName()); add(town); add(new Label("townLabel", "Town")); HandicapType postihnutie = new HandicapType(); handicapType = new DropDownChoice( "handicapType", new PropertyModel(postihnutie, "name"), HANDICAPTYPE_LIST); handicapType.setRequired(false); if (user.getHandicapType() != null) postihnutie.setName(user.getHandicapType().getName()); add(handicapType); add(new Label("handicapTypeLabel", "Handicap")); preferRegion = new CheckBox("preferRegion", new PropertyModel(properties, "preferRegion")); add(preferRegion); add(new Label("preferRegionLabel", "Preferujem")); add(new Label("registrationDateLabel", "Dátum registrácie:")); add(new Label("userRegistrationDateLabel", dateFormat.format(user.getRegistrationDate()))); password = new PasswordTextField("password", new PropertyModel(properties, "password")); add(password); password.setRequired(false); // add(passwordFeedback = new ComponentFeedbackPanel( // "passwordFeedback", password)); add(new Label("passwordLabel", "Heslo:")); passwordAgain = new PasswordTextField("passwordAgain", new PropertyModel(properties, "passwordAgain")); add(passwordAgain); passwordAgain.setRequired(false); // add(passwordAgainFeedback = new ComponentFeedbackPanel("passwordAgainFeedback", // passwordAgain)); add(new Label("passwordAgainLabel", "Heslo znova")); add(submit = new Button("submit", new ResourceModel("button.submit"))); // add(submitFeedback = new ComponentFeedbackPanel("submitFeedback", // submit)); }