Values of checkboxes not saved in database - java

I have a jsp page on which there are various checkboxes.
Some of checkboxes are disabled by default and are already selected. There is an option to create a new template and assign values to checkboxes. These values are saved into a DB.
My problem is that saved values of selected checkboxes are always two less than values that were selected by the user. On debugging the java code, I found that the passed values were as selected by the user. But the values of the disabled checkboxes are saved to the DB, and the last two values selected by the user are not saved to the DB.
I am hereby attaching the code which picks the selected values and code which saves the values of checkboxes.
Code to pick selected checkbox values.
public ActionForward listSave(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HardwareKey key = SecurityUtils.getKeySecurity();
key.isFeaturePresent(HardwareKey.WS_DATA_EXCHANGE);
DataExchangeTemplateForm thisForm = (DataExchangeTemplateForm) form;
DataExchangeService service = (DataExchangeService) ServiceLocator
.getServiceWithName(DataExchangeService.class.getName());
ActionMessages errors = new ActionMessages();
Integer dexTemplateId = thisForm.getTemplateId();
String[] paramValues = request.getParameterValues("isRequiredFlag");
String[] fieldIds = request.getParameterValues("fieldId");
String[] dataTypeIds = request
.getParameterValues("dexDataType.dataTypeId");
String templateType = request.getParameter("templateType");
boolean isDexTemplate = false;
String direction = thisForm.getDirection();
String dexTemplateName = thisForm.getDexTemplateName();
if (Validator.isNullOrEmpty(dexTemplateName)) {
ActionMessage msg = new ActionMessage("error.data.exchange",
" Template name Can't be empty");
errors.add("error.data.exchange", msg);
saveErrors(request, errors);
return view(mapping, form, request, response);
}
String dexTemplateVersion = thisForm.getDexVersion();
if (Validator.isNotNullGreaterThanZero(dexTemplateId)) {
DexTemplate dexTemplateOld = (DexTemplate) service.getObject(
DexTemplate.class, dexTemplateId);
String profileNameOld = dexTemplateOld.getDescription();
if (!dexTemplateName.equalsIgnoreCase(profileNameOld)
&& service.isDuplicateTemplateName(dexTemplateName)) {
ActionMessage msg = new ActionMessage("error.data.exchange",
"Duplicate Template name");
errors.add("error.data.exchange", msg);
saveErrors(request, errors);
return view(mapping, form, request, response);
}
service.updateDexTemplateAndParams(dexTemplateName, direction,
dexTemplateId, dataTypeIds, paramValues, fieldIds,
dexTemplateVersion);
} else {
if (!service.isDuplicateTemplateName(dexTemplateName)) {
if(templateType != null && templateType.equals("extranetDex")) {
isDexTemplate = true;
}
dexTemplateId = service.saveDataExchangeTemplate(
dexTemplateName, direction, dexTemplateVersion, isDexTemplate);
// saving params...
service.saveDexTemplateParams(dexTemplateId, dataTypeIds,
paramValues, fieldIds);
} else {
ActionMessage msg = new ActionMessage("error.data.exchange",
"Duplicate Template name");
errors.add("error.data.exchange", msg);
saveErrors(request, errors);
return view(mapping, form, request, response);
}
}
Code To Save Selected Checkbox values:
public void saveDexTemplateParams(Integer dexTemplateId,
String[] dataTypeIds, String[] paramValues, String[] fieldIds)
throws BaajaException {
DexTemplate dexTemplate = (DexTemplate) getObject(DexTemplate.class,
dexTemplateId);
hibernateInitialize(dexTemplate);
int fieldOrder = 1;
if(paramValues!=null){
for (int i = 0; i < paramValues.length; i++) {
if (!Validator.isNullOrEmpty(paramValues[i])
&& paramValues[i].equalsIgnoreCase("true")) {
DexTemplateField templatefield = new DexTemplateField();
DexField dexField = (DexField) getObject(DexField.class,
Integer.parseInt(fieldIds[i]));
templatefield.setDexField(dexField);
templatefield.setDexTemplate(dexTemplate);
templatefield.setFieldOrder(fieldOrder++);
saveObject(templatefield);
}
Pls Suggest any possible solution.

Check if the name/id of the last 2 checkboxes are the same as for the other checkboxes.
It is recommended that if you are using Struts framework, use FormBean to attach to the JSP Form. In that FormBean, declare ArrayList with the name same as the property attribute of <html:checkbox> . This will help you minimize your support/maintenance time.

Related

How to display a Postgres aliased field in Vaadin field?

This is a query I wrote:
public List<PrRevamps> fetchRevampHistory(String refNo) {
List<PrRevamps> list = dsl.select(
DSL.concat(
Tables.PR_REVAMPS.PR_REVAMP_CODE,DSL.val("-"),
Tables.PR_REVAMP_CODES.PR_DESCRIPTION
).as("DESCRIPTION"),
Tables.PR_REVAMPS.PR_REVAMP_DATE,
Tables.PR_REVAMPS.PR_KEY)
.from(Tables.PR_REVAMP_CODES,Tables.PR_REVAMPS)
.where(Tables.PR_REVAMPS.PR_REVAMP_CODE.equal(Tables.PR_REVAMP_CODES.PR_CODE))
.and(Tables.PR_REVAMPS.PR_PROP_REF_NO.equal(refNo))
.fetchInto(PrRevamps.class);
return list;
}
and I need to display revampCode and description in one row in vaadin grid.
i.e "A-Marshall"
This is the grid code below:
private void populateRevampGrid() {
Object ref = serv.getAttribute("ref");
String propRef = "";
if(ref != null) {
propRef = (String)ref;
List<PrRevamps> list = getService().fetchRevampHistory(propRef);
if(!list.isEmpty()) {
revampGrid.setContainerDataSource(new BeanItemContainer<>(list));
//revampGrid.addColumn("prRevampCode").setHeaderCaption("REVAMP DESCRIPTION");
revampGrid.removeColumn("prKey");
revampGrid.removeColumn("prLeaseType");
revampGrid.removeColumn("prPropRefNo");
revampGrid.getColumn("prRevampDate").setHeaderCaption("REVAMP DATE");
revampGrid.getColumn("prRevampCode").setHeaderCaption("REVAMP TYPE");
} else {
clearfields();
Notification.show("list is empty",Type.ERROR_MESSAGE.WARNING_MESSAGE);
}
}
}
As I understand, you have the description field, that has the desired value.
If not, you can add properties, generated from an object on the fly. But for this, you will need to use Container.
The full description can be found on Vaadin documentation https://vaadin.com/docs/v7/framework/datamodel/datamodel-container.html (see GeneratedPropertyContainer)

How to translate a DTO in Struts 2

We are working for internationalizing an old application with some dirty code. For example, we have an object DTO InstrumentDto:
private String label;
private Quotation quotation;
private ExprQuote quoteExp;
public String getTypeCouponCouru() {
if (this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_CPN_INCLUS)
|| this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_INTERET)) {
return "Coupon attaché";
} else if(this.quoteExp.getCode().equals(Constants.INS_QUOTE_EXPR_PCT_NOMINAL_PIED_CPN)){
return "Coupon détaché";
} else {
return "";
}
}
public String getFormattedLabel() {
StringBuilder formattedLabel = new StringBuilder(this.label);
Quotation quote = this.quotation;
if (this.quotation != null) {
formattedLabel.append(" ");
formattedLabel.append(FormatUtil.formatDecimal(this.quotation.getCryQuote());
if (this.quoteExp.getType().equals("PERCENT")) {
formattedLabel.append(" %");
} else {
formattedLabel.append(" ");
formattedLabel.append(this.quotation.getCurrency().getCode());
}
formattedLabel.append(" le ");
formattedLabel.append(DateUtil.formatDate(this.quotation.getValoDate()));
}
return formattedLabel.toString();
}
Then, those methods are used on JSPs. For example for getFormattedLabel(), we have :
<s:select name = "orderUnitaryForm.fieldInstrument"
id = "fieldInstrument"
list = "orderUnitaryForm.instrumentList"
listKey = "id"
listValue = "formattedLabel" />
IMO, the first method doesn't have its place on the DTO. We are expecting the view to manage the label to print. And in this view (the JSP), no problem to translate those words.
Additionally, this method is just used in 2 JSP. Not a problem to "repeat" the conditional tests.
But it's more difficult for getFormattedLabel() : this method is used in a lot of JSP, and the building of the formatted label is "complicated". And it's not possible having the i18n service in the DTO.
So how to do that ?
Your code in getFormattedLabel() seems to be business logic.
A DTO is a simple object without any complex test/behavior (see wiki definition).
IMO, you should move this chunk of code to your Action and split your *.properties file like this:
Your *.properties:
message1= {0} % le {1}
message2= {0} {1} le {2}
Your Action:
public MyAction extends ActionSupport {
public String execute(){
//useful code here
InstrumentDto dto = new InstrumentDto();
StringBuilder formattedLabel = new StringBuilder(label);
if (this.quotation != null) {
String cryQuote = FormatUtil.formatDecimal(this.quotation.getCryQuote());
String date = DateUtil.formatDate(this.quotation.getValoDate());
if (this.quoteExp.getType().equals("PERCENT")) {
formattedLabel.append(getText("message1", new String[] { cryQuote, date }));
} else {
String cryCode = this.quotation.getCurrency().getCode();
formattedLabel.append(getText("message2", new String[] { cryQuote, cryCode, date }));
}
}
dto.setFormattedLabel(formattedLabel);
}
}
Hope this will help ;)

JPA.em().find returns null for existing object

I have a problem with JPA in play framework 2.1. Here is my situation:
I have action method which handles sign up for my application (User fills email and password and submits the form). In this method I check if the user exists in my database and if not I create new one. Here is simplified code which shows how it works:
public Result signUpSubmit(String email, String password) {
User existingUser = (User) User.find("SELECT u FROM User u WHERE u.email=?", email).get(0);
if (existingUser != null) {
// code which handles existing user
} else {
User newUser = new User(email, password);
Users.persistUserAsync(newUser); // calls JPA.em().persist(newUser) asynchronously
// but I wait until the save is done
// After this call I have new row in DB with newUser (with assigned id)
System.out.println(newUser.id); // prints id which was assigned to new user in DB
User u = (User)JPA.em().find(User.class, newUser.id)
System.out.println(u.id); // throws NullPointer exception, because u is null
}
return renderJapid();
}
Can you tell me the reason why I get the null from the second find query?
public boolean persistUserAsync(User) {
final ModelCreatingJob modelCreatingJob = new ModelCreatingJob(user);
final Promise<Boolean> promisedSave = modelCreatingJob.now();
final Boolean saved = promisedSave.get(20000L);
return saved;
}
The ModelCreatingJob does only this:
return JPA.withTransaction(new F.Function0<Boolean>() {
#Override
public Boolean apply() throws UserLockedException, UserNotFoundException {
return model.validateAndCreate();
}
});
Strange is that when I remove first find (just leave newUser = null) on second find I get valid user object.

Spring form:select - multiple does not select first option by default

I have been working on a Spring project that makes use of the Spring form taglib (http://www.springframework.org/tags/form).
I am using some multiple select boxes to indicate some options (Country, factory,...)When I pass an entire list to the select - all is well: the first option of the select list is selected by default. However, when a user is from a specific country, the list is filtered and only his country is shown. In this case the first element is not selected by default.
JSP page:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<form:select path="countryValues" multiple="true" size="9" style="width:192px;" cssErrorClass="field-error">
<form:options items="${command.countries}" itemValue="countryCode" itemLabel="correctDisplayString"/>
</form:select>
Command.java
public List<CountryMaster> getCountries() {
return countries;
}
public void setCountries(List<CountryMaster> countries) {
this.countries = countries;
}
Controller.java
#RequestMapping(value = "/overview", method = RequestMethod.GET)
public String overview(HttpServletRequest request, Model model) {
Attrs attrs = getAttrs(request);
UserLocale.initUser(getUser(request));
User user = UserLocale.getUser();
List<FactoryMaster> factoryList = getFactoryList(attrs);
List<CountryMaster> countryList = getCountryList(attrs);
Command command = initCommand(attrs);
model.addAttribute(command);
if(user.hasRole(User.NORMAL)&& user.getCountryCode() != null){
if(countries == null){
countries= getDaoBuilder().getDaoCountry().countryMap();
}
String isoCode = countries.get(user
.getCountryCode());
List<CountryMaster> buffer = new ArrayList<CountryMaster>();
for(CountryMaster i : countryList){
if(isoCode.equalsIgnoreCase(i.getIsoCode())){
buffer.add(i);
}
}
System.out.println("List size: "+buffer.size());
command.setCountries(buffer);
}
else{
command.getCountries().addAll(getCountryList(attrs));
}
command.getModels().addAll(getModelList(attrs));
command.setBrands(getBrandList(attrs));
return "/reporting/overview";
}
private List<CountryMaster> getCountryList(Attrs attrs) {
List<CountryMaster> result = new ArrayList<CountryMaster>();
CountryMaster ct = new CountryMaster(CountryMaster.ISO_COUNTRY_JOKER, 00);
ct.setDescription("ALL");
result.add(ct);
result.addAll(attrs.countryList);
return result;
}
On the HTML page, I can see in other lists that the first element has the attribute selected="selected". Anybody have any idea why this is not the case when I manipulate my list? Or does anyone know what is resposible for this selected attribute allocation? (Is this javascript, java attribute,...?)
Thanks in advance!
Turns out the value of the listbox can be set: this piece of code made it quite an easy fix:
public String overview(HttpServletRequest request, Model model) {
Attrs attrs = getAttrs(request);
UserLocale.initUser(getUser(request));
User user = UserLocale.getUser();
List<FactoryMaster> factoryList = getFactoryList(attrs);
List<CountryMaster> countryList = getCountryList(attrs);
Command command = initCommand(attrs);
model.addAttribute(command);
if(user.hasRole(User.NORMAL)&& user.getCountryCode() != null){
if(countries == null){
countries= getDaoBuilder().getDaoCountry().countryMap();
}
String isoCode = countries.get(user
.getCountryCode());
List<CountryMaster> buffer = new ArrayList<CountryMaster>();
for(CountryMaster i : countryList){
if(isoCode.equalsIgnoreCase(i.getIsoCode())){
buffer.add(i);
}
}
System.out.println("List size: "+buffer.size());
command.setCountries(buffer);
// FIXED SELECTION OF ELEMENT
command.setFactoryValues(new String[]{isoCode});
// FIXED SELECTION OF ELEMENT
}
else{
command.getCountries().addAll(getCountryList(attrs));
}
command.getModels().addAll(getModelList(attrs));
command.setBrands(getBrandList(attrs));
return "/reporting/overview";
}
This way, you set the value of the listbox using code, and when the page is opened - the value is already there, making it selected by default.

Bound values are not getting updated from editable datatable without setting ID in JDK1.5

Bound values are not getting updated from editable data table without setting ID in JDK 1.5. But the same does work without setting ID in JDK 1.6.
Does anyone know why? Thanks
Code, Bean part
public void setDataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
public HtmlDataTable getDataTable() {
if (dataTable == null)
setEditableDataTable();
return dataTable;
}
private void setEditableDataTable() {
dataTable = new HtmlDataTable();
dataTable.setValueBinding("value",
createValuebinding("#{testBean.stringList}"));
dataTable.setVar("items");
for (int i = 0; i < getDatastable().get(i).size(); i++) {
UIColumn column = new UIColumn();
dataTable.getChildren().add(column);
HtmlOutputText header = new HtmlOutputText();
header.setValue("Header "+i);
column.setHeader(header);
HtmlInputText input = new HtmlInputText();
input.setValueBinding("value", createValuebinding("#{items[" + i
+ "]}"));
column.getChildren().add(input);
}
}
private ValueBinding createValuebinding(String valueExpression) {
return FacesContext.getCurrentInstance().getApplication()
.createValueBinding(valueExpression);
}
JSP part
<h:dataTable binding="#{testBean.dataTable}" >
</h:dataTable>
Solution
Give id for the datatable

Categories

Resources