All errors not added to PageMessages - salesforce

I am throwing some custom exceptions in my controller and I'm noticing when there are multiple errors, the errors do not display all at once. Rather they display one at a time on the page. I'm using the pageMessages component.
I think the issue is in the controller on how I'm adding the errors in the catch block for all the different methods.
Here is my class:
public with sharing class CallReportControllerExtension {
private Call_Report__c callReport;
public Boolean isEditMode {get; set;}
public List<Participants> participantLinesForPage {get; set;}
public List<ProductsPresented> productLinesForPage {get; set;}
public List<Tasks> taskLinesForPage {get; set;}
public CallReportControllerExtension(ApexPages.StandardController stdController) {
this.callReport = (Call_Report__c)stdController.getRecord();
isEditMode = isEditPage(ApexPages.currentPage().getParameters().get('save_new'));
refreshParticipantLineItems();
refreshProductLineItems();
refreshTaskLineItems();
}
public PageReference save() {
Savepoint sp = Database.setSavepoint();
try {
insert callReport;
upsertParticipants(callReport.Id);
upsertProducts(callReport.Id);
upsertTasks(callReport.Id);
}
catch(Exception ex) {
ApexPages.addMessages(ex);
Database.rollback(sp);
callReport = callReport.clone(false);
return null;
}
PageReference pageRef = new ApexPages.StandardController(callReport).view();
pageRef.setRedirect(true);
return pageRef;
}
public PageReference updateCallReport() {
Savepoint sp = Database.setSavepoint();
try {
update callReport;
upsertParticipants(callReport.Id);
upsertProducts(callReport.Id);
upsertTasks(callReport.Id);
}
catch(Exception ex) {
ApexPages.addMessages(ex);
Database.rollback(sp);
return null;
}
PageReference pageRef = new ApexPages.StandardController(callReport).view();
pageRef.setRedirect(true);
return pageRef;
}
private PageReference upsertParticipants(String callreportid) {
List<Participant__c> recordsToUpsert = new List<Participant__c>();
for(Participants parts : participantLinesForPage) {
if(parts.participantLine.Call_Report__c == null) {
Participant__c p = new Participant__c();
p.Call_Report__c = callreportid;
if(!String.isEmpty(parts.accountId)) {
p.Account__c = parts.accountId;
} else {
p.Account__c = null;
}
if(!String.isEmpty(parts.contactId)) {
p.Contact__c = parts.contactId;
} else {
p.Contact__c = null;
}
if(!String.isEmpty(parts.userId)) {
p.User__c = parts.userId;
} else {
p.User__c = null;
}
recordsToUpsert.add(p);
}
else {
if(!String.isEmpty(parts.accountId)) {
parts.participantLine.Account__c = parts.accountId;
} else {
parts.participantLine.Account__c = null;
}
if(!String.isEmpty(parts.contactId)) {
parts.participantLine.Contact__c = parts.contactId;
} else {
parts.participantLine.Contact__c = null;
}
if(!String.isEmpty(parts.userId)) {
parts.participantLine.User__c = parts.userId;
} else {
parts.participantLine.User__c = null;
}
recordsToUpsert.add(parts.participantLine);
}
}
if(!recordsToUpsert.isEmpty() && recordsToUpsert.size() > 0) {
try {
upsert recordsToUpsert;
}
catch(Exception ex) {
ApexPages.addMessages(ex);
return null;
}
}
return null;
}
private PageReference upsertProducts(String callreportid) {
List<Products_Presented__c> recordsToUpsert = new List<Products_Presented__c>();
for(ProductsPresented prodPresented : productLinesForPage) {
if(prodPresented.productLine.Call_Report__c == null) {
Products_Presented__c pp = new Products_Presented__c();
pp.Call_Report__c = callreportid;
if(!String.isEmpty(prodPresented.productId)) {
pp.Product__c = prodPresented.productId;
} else {
throw new CallReportException('The Product presented field is blank. Please select a product.');
}
pp.Notes__c = prodPresented.productLine.Notes__c;
pp.At_Risk__c = prodPresented.productLine.At_Risk__c;
recordsToUpsert.add(pp);
}
else {
if(!String.isEmpty(prodPresented.productId)) {
prodPresented.productLine.Product__c = prodPresented.productId;
} else {
throw new CallReportException('The Product presented field is blank. Please select a product.');
}
prodPresented.productLine.Notes__c = prodPresented.productLine.Notes__c;
prodPresented.productLine.At_Risk__c = prodPresented.productLine.At_Risk__c;
recordsToUpsert.add(prodPresented.productLine);
}
}
if(!recordsToUpsert.isEmpty() && recordsToUpsert.size() > 0) {
try {
upsert recordsToUpsert;
}
catch(Exception ex) {
ApexPages.addMessages(ex);
return null;
}
}
return null;
}
private PageReference upsertTasks(String callreportid) {
List<Task> recordsToUpsert = new List<Task>();
for(Tasks t : taskLinesForPage) {
if(t.taskLine.WhatId == null) {
Task task = new Task();
task.WhatId = callreportid;
if(!String.isEmpty(t.whoId)) {
task.WhoId = t.whoId;
} else {
task.WhoId = null;
}
if(String.isEmpty(t.userId)) throw new CallReportException('The Assigned To field is blank. Please select a user that is assigned this task.');
task.OwnerId = t.userId;
task.Subject = 'Call Report Task';
task.ActivityDate = t.taskLine.ActivityDate;
task.Description = t.taskLine.Description;
task.Status = 'Not Started';
task.Priority = 'Normal';
recordsToUpsert.add(task);
}
else {
if(!String.isEmpty(t.whoId)) {
t.taskLine.WhoId = t.whoId;
} else {
t.taskLine.WhoId = null;
}
if(String.isEmpty(t.userId)) throw new CallReportException('The Assigned To field is blank. Please select a user that is assigned this task.');
t.taskLine.OwnerId = t.userId;
t.taskLine.ActivityDate = t.taskLine.ActivityDate;
t.taskLine.Description = t.taskLine.Description;
recordsToUpsert.add(t.taskLine);
}
}
if(!recordsToUpsert.isEmpty() && recordsToUpsert.size() > 0) {
try {
upsert recordsToUpsert;
}
catch(Exception ex) {
ApexPages.addMessages(ex);
return null;
}
}
return null;
}
public PageReference addParticipant() {
Participant__c newRecord = new Participant__c();
participantLinesForPage.add(new Participants(participantLinesForPage.size(), newRecord, newRecord.Account__r.Id, newRecord.Account__r.Name, newRecord.Contact__r.Id, newRecord.Contact__r.Name, newRecord.User__r.Id, newRecord.User__r.Name));
return null;
}
public PageReference deleteParticipant() {
Integer selectId = Integer.valueOf(ApexPages.currentPage().getParameters().get('del'));
Participants toRemove = participantLinesForPage.get(selectId);
try {
if(toRemove.participantLine.Id != null) {
delete [select Id from Participant__c where Id =: toRemove.ParticipantLine.Id];
}
participantLinesForPage.remove(selectId);
} catch (Exception e) {
ApexPages.addMessages(e);
}
Integer iterate = 0;
for(Participants parts : participantLinesForPage) {
parts.iterate = iterate;
iterate +=1;
}
return null;
}
public PageReference addProduct() {
Products_Presented__c newRecord = new Products_Presented__c();
productLinesForPage.add(new ProductsPresented(productLinesForPage.size(), newRecord, newRecord.Product__r.Id, newRecord.Product__r.Name));
return null;
}
public PageReference deleteProduct() {
Integer selectId = Integer.valueOf(ApexPages.currentPage().getParameters().get('del'));
ProductsPresented toRemove = productLinesForPage.get(selectId);
try {
if(toRemove.productLine.Id != null) {
delete [select Id from Products_Presented__c where Id =: toRemove.productLine.Id];
}
productLinesForPage.remove(selectId);
} catch (Exception e) {
ApexPages.addMessages(e);
}
Integer iterate = 0;
for(ProductsPresented prods : productLinesForPage) {
prods.iterate = iterate;
iterate +=1;
}
return null;
}
public PageReference addTask() {
Task newRecord = new Task();
taskLinesForPage.add(new Tasks(taskLinesForPage.size(), newRecord, newRecord.Who.Id, newRecord.Who.Name, newRecord.Owner.Id, newRecord.Owner.Name));
return null;
}
public PageReference deleteTask() {
Integer selectId = Integer.valueOf(ApexPages.currentPage().getParameters().get('del'));
Tasks toRemove = taskLinesForPage.get(selectId);
try {
if(toRemove.taskLine.Id != null) {
delete [select Id from Task where Id =: toRemove.taskLine.Id];
}
taskLinesForPage.remove(selectId);
} catch (Exception e) {
ApexPages.addMessages(e);
}
Integer iterate = 0;
for(Tasks tasks : taskLinesForPage) {
tasks.iterate = iterate;
iterate +=1;
}
return null;
}
private void refreshParticipantLineItems() {
List<Participant__c> lineItems = [select Account__c, Account__r.Id, Account__r.Name, Contact__c, Contact__r.Id, Contact__r.Name, User__c, User__r.Id, User__r.Name, Spent_Amount__c, Call_Report__c from Participant__c where Call_Report__c =: callReport.Id];
participantLinesForPage = new List<Participants>();
Integer iterate = 0;
for(Participant__c p : lineItems) {
participantLinesForPage.add(new Participants(iterate, p, String.valueOf(p.Account__r.Id), p.Account__r.Name, String.valueOf(p.Contact__r.Id), p.Contact__r.Name, String.valueOf(p.User__r.Id), p.User__r.Name));
iterate += 1;
}
}
private void refreshProductLineItems() {
List<Products_Presented__c> prodsPresentedLineItems = [select Product__r.Id, Product__r.Name, Call_Report__c, Notes__c, At_Risk__c from Products_Presented__c where Call_Report__c =: callReport.Id];
productLinesForPage = new List<ProductsPresented>();
Integer iterate = 0;
for(Products_Presented__c pp : prodsPresentedLineItems) {
productLinesForPage.add(new ProductsPresented(iterate, pp, String.valueOf(pp.Product__r.Id), pp.Product__r.Name));
iterate += 1;
}
}
private void refreshTaskLineItems() {
List<Task> taskLineItems = new List<Task>();
if(callReport.Id != null) {
taskLineItems = [select Who.Id, Who.Name, ActivityDate, Description, WhatId, OwnerId, Owner.Id, Owner.Name from Task where WhatId =: callReport.Id];
}
taskLinesForPage = new List<Tasks>();
Integer iterate = 0;
for(Task t : taskLineItems) {
taskLinesForPage.add(new Tasks(iterate, t, String.valueOf(t.Who.Id), t.Who.Name, String.valueOf(t.Owner.Id), t.Owner.Name));
iterate += 1;
}
}
private Boolean isEditPage(String param) {
Boolean retval = true;
if(param != null) {
retval = false;
}
return retval;
}
class Participants {
public Integer iterate {get; set;}
public Participant__c participantLine {get; set;}
public String accountId {get; set;}
public String accountName {get; set;}
public String contactId {get; set;}
public String contactName {get; set;}
public String userId {get; set;}
public String userName {get; set;}
public Participants(Integer iterate, Participant__c participantLine, String accountId, String accountName, String contactId, String contactName, String userId, String userName) {
this.iterate = iterate;
this.participantLine = participantLine;
this.accountId = accountId;
this.accountName = accountName;
this.contactId = contactId;
this.contactName = contactName;
this.userId = userId;
this.userName = userName;
}
}
class ProductsPresented {
public Integer iterate {get; set;}
public Products_Presented__c productLine {get; set;}
public String productId {get; set;}
public String productName {get; set;}
public ProductsPresented(Integer iterate, Products_Presented__c productLine, String productId, String productName) {
this.iterate = iterate;
this.productLine = productLine;
this.productId = productId;
this.productName = productName;
}
}
class Tasks {
public Integer iterate {get; set;}
public Task taskLine {get; set;}
public String whoId {get; set;}
public String whoName {get; set;}
public String userId {get; set;}
public String userName {get; set;}
public Tasks(Integer iterate, Task taskLine, String whoId, String whoName, String userId, String userName) {
this.iterate = iterate;
this.taskLine = taskLine;
this.whoId = whoId;
this.whoName = whoName;
this.userId = userId;
this.userName = userName;
}
}
}
Thanks for any help.

For example you have four DML operations and the first operation falls, so the code does not continue to the second operation. So you only displays the first error on the page.
try {
action 1;
action 2;
action 3;
action 4;
} catch(Exception ex) {
ApexPages.addMessages(ex);
}
If it necessary you can change it to something like this.
try { action 1;}catch(exception ex){ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,ex.getMessage()));}
try { action 2;}catch(exception ex){ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,ex.getMessage()));}...
if(ApexPages.hasMessages())return null;

Related

Error when creating a pagination with apex

No errors on the apex class screen. An unexpected error occurs when you press the search button.
I got an error when I added the pagination code in the second half.
There was no problem before that.
Why?
public with sharing class AccountListCon {
static List<String> TARGET_FIELDS = new List<String>{
'Name'
};
public SearchCondition condition{ get;set; }
public List<AccountList__c> results { get;set; }
public String sortingField { get;set; }
public void init(){
this.condition = new SearchCondition();
this.results = new List<AccountList__c>();
}
public PageReference clear(){
init();
return null;
}
public PageReference search() {
if( condition.validate() ){
return null;
}
String soqlQuery = condition.getSoqlQuery();
System.debug('[soql] ' + soqlQuery);
try{
this.results = database.query(soqlQuery);
System.debug(this.results);
}catch(DmlException e){
ApexPages.addMessages(e);
System.debug('[DmlException]' + e);
}catch(Exception e){
ApexPages.addMessages(e);
System.debug('[Exception]' + e);
}
return null;
}
public PageReference sort(){
if(this.sortingField == null ){
return null;
}
if(this.sortingField == this.condition.sortkey){
this.condition.setOrderReverse();
}
else {
this.condition.sortkey = this.sortingField;
}
search();
return null;
}
public Class SearchCondition {
private Time JST_AM0 = Time.newInstance(9, 0, 0, 0);
public AccountList__c obj {get;set;}
public SearchCondition() {
this.obj = new AccountList__c();
sortkey = 'LastModifiedDate';
order = 'DESC';
}
public String getSoqlQuery(){
List<String> param = new String[]{ getFieldList(), getWhere(), getOrder() };
return String.format('SELECT {0} FROM AccountList__c {1} {2} LIMIT 500', param);
}
private String getFieldList(){
return String.join(TARGET_FIELDS, ',');
}
private String getWhere(){
List<String> param = new String[]{ };
--Omission--
if(param.isEmpty()){
return '';
}
return 'WHERE ' + String.join(param, ' AND ');
}
private String getOrder(){
List<String> param = new String[]{ sortkey, order };
return String.format('ORDER BY {0} {1}', param);
}
private DateTime adjustJSTtoGMS(DateTime day){
JST_AM0 = Time.newInstance(15, 0, 0, 0);
return Datetime.newInstance(day.date(), JST_AM0);
}
--Omission--
private static final Integer PAGE_SIZE = 10;
public Integer currentPage {get; set;}
public Integer totalPage {get; set;}
private ApexPages.StandardSetController ssController;
public Boolean getEnablePrev(){
return ssController.getHasPrevious();
}
public Boolean getEnableNext(){
return ssController.getHasNext();
}
public void PagingCtrl(){
}
public PageReference searchinit() {
ssController = new ApexPages.StandardSetController([SELECT Id, Name FROM Account]);
currentPage = ssController.getPageNumber();
ssController.setPageSize(PAGE_SIZE);
totalPage = (Integer)Math.ceil((Decimal)ssController.getResultSize() / PAGE_SIZE);
return null;
}
public void next() {
ssController.next();
currentPage = ssController.getPageNumber();
}
public void prev() {
ssController.previous();
currentPage = ssController.getPageNumber();
}
public List<Account> getAccountList(){
return (List<Account>)ssController.getRecords();
}
}
Attempt to de-reference a null object
FATAL_ERROR Class.AccountListCon.getEnablePrev: line 292, column 1
public Boolean getEnablePrev(){
return ssController.getHasPrevious();
}
It looks like getEnablePrev() is being called prior to searchInit(), where ssController is initialized. Your Visualforce page may be attempting to render the pagination area prior to completing the initialization of the required data; we couldn't tell the reason why without seeing the relevant portions of your Visualforce page.

Hibernate Transformers.aliasToBean populate primary fields

I am trying to get list of Tbcompany table using Transformers.aliasToBean with 2 primary key fields.
I am using SQL SERVER and Hibernate 3.2.4.
My table has 2 primary fields.
Tbcompany.class
public class Tbcompany {
private TbcompanyId id;
private String hcompanycode;
public TbcompanyId getId() {
return id;
}
public void setId(TbcompanyId id) {
this.id = id;
}
public String getHcompanycode() {
return hcompanycode;
}
public void setHcompanycode(String hcompanycode) {
this.hcompanycode = hcompanycode;
}
}
And inside TbcompanyId.class :
public class TbcompanyId
implements Serializable
{
private String companycode;
private String companyname;
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof TbcompanyId)) {
return false;
}
TbcompanyId other = ((TbcompanyId) o);
if (this.companycode == null) {
if (other.companycode!= null) {
return false;
}
} else {
if (!this.companycode.equals(other.companycode)) {
return false;
}
}
if (this.companyname == null) {
if (other.companyname!= null) {
return false;
}
} else {
if (!this.companyname.equals(other.companyname)) {
return false;
}
}
return true;
}
public int hashCode() {
int rtn = 17;
rtn = (rtn* 37);
if (this.companycode!= null) {
rtn = (rtn + this.companycode.hashCode());
}
rtn = (rtn* 37);
if (this.companyname!= null) {
rtn = (rtn + this.companyname.hashCode());
}
return rtn;
}
public String getCompanycode() {
return companycode;
}
public void setCompanycode(String companycode) {
this.companycode = companycode;
}
public String getCompanyname() {
return companyname;
}
public void setCompanyname(String companyname) {
this.companyname = companyname;
}
I want to create a form and use Transformers.aliasToBean to populate the form .
This query :
Query q;
q = session.createQuery("SELECT a.id.companycode as companycode,a.id.companyname as companyname,a.hcompanycode as hcompanycode FROM Tbcompany a");
q.setResultTransformer(Transformers.aliasToBean(Tbcompany.class));
list = q.list();
gives me an error of :
org.hibernate.PropertyNotFoundException: Could not find setter for companycode on class com.loansdb.data.Tbcompany
While this query :
Query q;
q = session.createQuery("SELECT a.id.companycode,a.id.companyname,a.hcompanycode as hcompanycode FROM
Tbcompany a");
q.setResultTransformer(Transformers.aliasToBean(Tbcompany.class));
list = q.list();
gives me this error :
org.hibernate.PropertyNotFoundException: Could not find setter for 0 on class com.loansdb.data.Tbcompany
Does anyone know how to do this?
The aliasToBean transformer use the name of the SQL columns returned and try to find a field with the same name on the class target that have a set method created.
So, your query returns a a.id.companycode:
SELECT a.id.companycode as companycode,a.id.companyname as companyname,a.hcompanycode as hcompanycode FROM Tbcompany a
The error said:
org.hibernate.PropertyNotFoundException: Could not find setter for companycode on class com.loansdb.data.Tbcompany
And your Tbcompany class does not have a setter to companycode.
So, to correct your Tbcompany class and looking your query, seems to me that the class it's something like:
public class Tbcompany {
private String companycode;
private String companycode;
private String companyname;
public String setCompanycode(String companycode) {
this.companycode = companycode;
}
// create the constructor, getters and setters
}

Why are Collection properties indexed in objectify, sometimes?

In objectify, when I define a collection property with String datatype,
#IgnoreSave(IfEmpty.class)
private Set<String> collectionProperty = new HashSet<>();
and then look at a record in datastore, it appears indexed even though I have not annotated it with #Index.
Contrary, when I use a complex Object instead String, it does not appear as indexed.
Why are Collection properties indexed sometimes and sometimes not? And is there a way to determine this?
--
Unmodified code and screenshot from admin console/datastore:
#Entity
#Cache(expirationSeconds = 900)
public class Item extends StringId implements Serializable {
private static final Logger log = Logger.getLogger(Item.class.getSimpleName());
private static final long serialVersionUID = 1;
// Constructors
private Item() {}
#Nonnull
private static Item create(#Nonnull String itemId) {
Item item = (Item) new Item().setId(itemId);
item.piecesFromId();
log.info("item = " + JsonHelper.logToJson(item));
return item;
}
#Nonnull
public static Item create(#Nonnull String provider, #Nonnull String type, #Nonnull String identifier) {
String itemId = IdHelper.createItemId(provider, type, identifier);
Item item = ((Item) new Item().setId(itemId))
.setProvider(provider)
.setType(type)
.setIdentifier(identifier);
log.info("item = " + JsonHelper.logToJson(item));
return item;
}
#Nonnull
public static Item loadOrCreate(#Nonnull String itemId) {
Item item = ofy().load().type(Item.class).id(itemId).now();
if (item == null) {
item = Item.create(itemId);
}
return item;
}
#Nullable
public static Item load(#Nonnull String itemId) {
return ofy().load().type(Item.class).id(itemId).now();
}
#OnLoad
private void piecesFromId() {
provider = IdHelper.getProvider(id);
type = IdHelper.getType(id);
identifier = IdHelper.getIdentifier(id);
}
public Item save() {
ofy().defer().save().entity(this);
return this;
}
#OnSave
private void integrity() {
if (id == null) { throw new RuntimeException("Id must not be null."); }
if (itemPreview == null) { throw new RuntimeException("itemPreview must not be null."); }
if (provider == null || type == null || identifier == null) { throw new RuntimeException("provider, type and identifier must not be null."); }
if (!id.equals(IdHelper.createItemId(provider, type, identifier))) { throw new RuntimeException("id does not coincide with provider, type and identifier."); }
if (!id.equals(itemPreview.getItemId())) { throw new RuntimeException("id does not coincide with id in itemPreview."); }
}
#OnSave
private void timestamp() {
if (created == null) {
created = System.currentTimeMillis();
}
}
// Properties
#Ignore
private String provider;
#Ignore
private String type;
#Ignore
private String identifier;
#Ignore // json
private ItemPreview itemPreview;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> subscribedUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> notifyUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfEmpty.class)
private Set<String> blacklistingUserIds = new HashSet<>();
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
private Long created;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfDefault.class)
#Index
private Status status = Status.ACTIVE;
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfNull.class)
private String suspensionNotice;
// Json
#ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
#IgnoreSave(IfNull.class)
private String itemPreviewJson;
private static Type itemPreviewType = new TypeToken<ItemPreview>(){}.getType();
#OnLoad
private void itemPreviewFromJson() {
if (itemPreviewJson != null) {
itemPreview = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
.fromJson(itemPreviewJson, itemPreviewType);
}
}
#OnSave
private void itemPreviewToJson() {
itemPreviewJson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
.toJson(itemPreview, itemPreviewType);
}
// Accessors
public String getProvider() {
return provider;
}
public Item setProvider(String provider) {
this.provider = provider;
return this;
}
public String getType() {
return type;
}
public Item setType(String type) {
this.type = type;
return this;
}
public String getIdentifier() {
return identifier;
}
public Item setIdentifier(String identifier) {
this.identifier = identifier;
return this;
}
public ItemPreview getItemPreview() {
return itemPreview;
}
public Item setItemPreview(ItemPreview itemPreview) {
this.itemPreview = itemPreview;
return this;
}
public Set<String> getSubscribedUserIds() {
return subscribedUserIds;
}
public Item setSubscribedUserIds(Set<String> subscribedUserIds) {
this.subscribedUserIds = subscribedUserIds;
return this;
}
public Set<String> getNotifyUserIds() {
return notifyUserIds;
}
public Item setNotifyUserIds(Set<String> notifyUserIds) {
this.notifyUserIds = notifyUserIds;
return this;
}
public Set<String> getBlacklistingUserIds() {
return blacklistingUserIds;
}
public Item setBlacklistingUserIds(Set<String> blacklistingUserIds) {
this.blacklistingUserIds = blacklistingUserIds;
return this;
}
public Long getCreated() {
return created;
}
public Item setCreated(Long created) {
this.created = created;
return this;
}
public Status getStatus() {
return status;
}
public Item setStatus(Status status) {
this.status = status;
return this;
}
public String getSuspensionNotice() {
return suspensionNotice;
}
public Item setSuspensionNotice(String suspensionNotice) {
this.suspensionNotice = suspensionNotice;
return this;
}
// Collections
public static Map<String, Item> loadAll(Set<String> itemIds) {
return ofy().load().type(Item.class).ids(itemIds);
}
}

JavaFX - How do I access the result(ObservableList) from a service?

How do I access the returned result from a service? The result is queried from the database and added to a ObservableList. I have a checkbox and wanted its value to depend on the result from the database.
How do I bind the checkbox so that its value(checked/unchecked) will depend on the rs.getString("studentForm137") field.
//cboxForm137.selectedProperty().bind(//I don't know the codes to bind checkbox);
Service
final Service<ObservableList<Student>> service = new Service<ObservableList<Student>>()
{
#Override
protected Task<ObservableList<Student>> createTask()
{
return new Task<ObservableList<Student>>()
{
#Override
protected ObservableList<Student> call() throws Exception
{
for (int i = 0; i < 250; i++)
{
updateProgress(i, 250);
Thread.sleep(2);
}
return student.display();
}
};
}
};
service.start();
Student Class
public class Student extends Person {
private SimpleStringProperty form137;
private SimpleStringProperty form138;
private SimpleStringProperty goodMoralCertificate;
private SimpleStringProperty birthCertificate;
private SimpleStringProperty highschoolDiploma;
public Student()
{
super();
}
public Student(String lastName, String firstName, String middleName,
String cpNumber, String address, String dateOfBirth,
String placeOfBirth, String emailAddress, String gender,
String fathersName, String mothersName,
String form137, String form138, String goodMoralCertificate,
String birthCertificate, String highschoolDiploma)
{
super(lastName, firstName, middleName,
cpNumber, address, dateOfBirth, placeOfBirth, emailAddress, gender,
fathersName, mothersName);
this.form137 = new SimpleStringProperty(form137);
this.form138 = new SimpleStringProperty(form138);
this.goodMoralCertificate = new SimpleStringProperty(goodMoralCertificate);
this.birthCertificate = new SimpleStringProperty(birthCertificate);
this.highschoolDiploma = new SimpleStringProperty(highschoolDiploma);
}
//form137
public String getForm137()
{
return form137.get();
}
public void setForm137(String form137)
{
this.form137.set(form137);
}
public StringProperty form137Property()
{
return form137;
}
//form138
public String getForm138()
{
return form138.get();
}
public void setForm138(String form138)
{
this.form138.set(form138);
}
public StringProperty form138Property()
{
return form138;
}
//goodMoralCertificate
public String getGoodMoralCertificate()
{
return goodMoralCertificate.get();
}
public void setGoodMoralCertificate(String goodMoralCertificate)
{
this.goodMoralCertificate.set(goodMoralCertificate);
}
public StringProperty goodMoralCertificateProperty()
{
return goodMoralCertificate;
}
//birthCertificate
public String getBirthCertificate()
{
return birthCertificate.get();
}
public void setBirthCertificate(String birthCertificate)
{
this.birthCertificate.set(birthCertificate);
}
public StringProperty birthCertificateProperty()
{
return birthCertificate;
}
//highschoolDiploma
public String getHighschoolDiploma()
{
return highschoolDiploma.get();
}
public void setHighschoolDiploma(String highschoolDiploma)
{
this.highschoolDiploma.set(highschoolDiploma);
}
public StringProperty highschoolDiplomaProperty()
{
return highschoolDiploma;
}
#Override
public ObservableList display()
{
Connection c = null;
PreparedStatement pst = null;
ResultSet rs = null;
ObservableList<Student> student = FXCollections.observableArrayList();
try
{
c = MySqlConnection.connect();
String SQL = "SELECT * " +
"FROM students ";
pst = c.prepareStatement(SQL);
rs = pst.executeQuery();
while(rs.next())
{
student.add(new Student(rs.getString("studentLastName"),
rs.getString("studentFirstName"),
rs.getString("studentMiddleName"),
rs.getString("studentCPNumber"),
rs.getString("studentAddress"),
rs.getString("studentDateOfBirth"),
rs.getString("studentPlaceOfBirth"),
rs.getString("studentEmailAddress"),
rs.getString("studentGender"),
rs.getString("studentFathersName"),
rs.getString("studentMothersName"),
rs.getString("studentForm137"),
rs.getString("studentForm138"),
rs.getString("studentGMC"),
rs.getString("studentNSO"),
rs.getString("studentHSDiploma")));
}
}
catch(Exception e)
{
System.out.println("Error on Building Data");
}
finally
{
try
{
PublicClass.closeConnection(c, pst, rs);
}
catch (SQLException ex)
{
Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
}
}
return student;
}
}

How to add sublist in wpf using mvvm?

namespace colourchanges
{
public class Group
{
public string Name { get; set; }
//its a class for adding parent list using group class
}
public class EmployeeTree : INotifyPropertyChanged
{
public EmployeeTree()
{
this.GroupStaff = new List<Group>();
GroupStaff.Add(new Group { Name = "Designers" });
GroupStaff.Add(new Group { Name = "Developers" });
GroupStaff.Add(new Group { Name = "Managers" });
//here we are declaring list for adding parent list
}
private List<Group> _GroupStaff;
public List<Group> GroupStaff
{
get { return _GroupStaff; }
set
{
_GroupStaff = value;
RaisePropertyChanged("GroupStaff");
}
}
//creates a list for parentlist
private Group _selectedGroupStaff;
public Group selectedGroupStaff
{
get { return _selectedGroupStaff; }
set
{
_selectedGroupStaff = value;
if (selectedGroupStaff.Name == "Designers")
{
City = "Chennai";
Country = "India";
Email = "Designer#gmail.com";
MobileNo = 9094117917;
Address = "Annanagar";
}
else if (selectedGroupStaff.Name == "Developers")
{
City = "Trichy";
Country = "India";
Email = "Developer#gmail.com";
MobileNo = 9094667878;
Address = "Koyambedu";
}
else if (selectedGroupStaff.Name == "Managers")
{
City = "Salem";
Country = "India";
Email = "Manager#gmail.com";
MobileNo = 9094154678;
Address = "Arumbakkam";
}
RaisePropertyChanged("selectedGroupStaff");
}
}//for selecting parent list in order to bind to textbox
private string _City;
private string _Country;
private string _Email;
private long _MobileNo;
private string _Address;
//properties of parent list to bind to textbox
public string City
{
get { return _City; }
set
{
_City = value;
RaisePropertyChanged("City");
}
}
public string Country
{
get { return _Country; }
set
{
_Country = value;
RaisePropertyChanged("Country");
}
}
public string Email
{
get { return _Email; }
set
{
_Email = value;
RaisePropertyChanged("Email");
}
}
public long MobileNo
{
get { return _MobileNo; }
set
{
_MobileNo = value;
RaisePropertyChanged("MobileNo");
}
}
public string Address
{
get { return _Address; }
set
{
_Address = value;
RaisePropertyChanged("Address");
}
}
///raise property changed event handler code
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
//how to add sub list for designers developers and managers in the constructor
Let the following be your Model class
public class Group
{
private string _City;
private string _Country;
private string _Email;
private long _MobileNo;
private string _Address;
public Group()
{
Items = new ObservableCollection<Group>();
}
public ObservableCollection<Group> Items { get; set; }
}
and at the ViewModel's constructor, you can add the Items.
public EmployeeTree()
{
this.GroupStaff = new List<Group>();
Group rootGroup = new Group(){Name ="Manager"};
Group childGroup = new Group(){Name = "Developer"};
rootGroup.Items.Add(childGroup);
this.GroupStaff.Add(rootGroup);
}
This is for Hierarchical structure. Hope you are looking for this.
And your XAML should be like this
<TreeView Name="GroupTreeView">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Items}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>

Resources