Error when creating a pagination with apex - salesforce

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.

Related

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
}

Azure AD B2C with Graph API - how to get/set user's email?

I add users to Azure AD B2C with Graph API but I don't get it how to store users' email (the primary one). Which field here is the user's primary email address?
As I read here on SO there's no way to populate values in Authentication contact info. It this correct?
Here's how I do it:
public async Task<AdUser> GetUserByObjectId(Guid objectId)
{
string userJson = await SendGraphGetRequest("/users/" + objectId, null);
JObject jUser = JObject.Parse(userJson);
return new AdUser(jUser);
}
internal AdUser(JObject jUser)
{
AccountEnabled = jUser["accountEnabled"].Value<bool>();
CompanyName = jUser["companyName"].Value<string>();
Department = jUser["department"].Value<string>();
DisplayName = jUser["displayName"].Value<string>();
FirstName = jUser["givenName"].Value<string>();
JobTitle = jUser["jobTitle"].Value<string>();
LastName = jUser["surname"].Value<string>();
MailNickname = jUser["mailNickname"].Value<string>();
Mobile = jUser["mobile"].Value<string>();
ObjectId = new Guid(jUser["objectId"].Value<string>());
List<string> mailList = new List<string>(jUser["otherMails"].Count());
mailList.AddRange(jUser["otherMails"].Select(mail => mail.Value<string>()));
OtherMails = mailList.AsReadOnly();
Phone = jUser["telephoneNumber"].Value<string>();
List<(string type, string value)> signInNames = jUser["signInNames"].Select(jToken => (jToken["type"].Value<string>(), jToken["value"].Value<string>())).ToList();
SignInNames = signInNames.AsReadOnly();
UserPrincipalName = jUser["userPrincipalName"].Value<string>();
UserType = jUser["userType"].Value<string>();
}
and here's the Email property of the AdUser:
public string Email
{
get
{
if (SignInNames.Count > 0 && SignInNames[0].type == "emailAddress")
return SignInNames[0].value;
if (OtherMails.Count > 0)
return OtherMails[0];
throw new InvalidOperationException("Don't know where to get user Email");
}
}
You need to make a PATCH request to the users endpoint
{baseurl}/{tenantId}/users?api-version={apiVersion}
Don't forget you access token in the auth header:
Authorization: Bearer {accessToken}
Here's an example model (Java) with methods for calculating and setting the sign-in email on a user object:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
import java.util.List;
#JsonIgnoreProperties(ignoreUnknown = true)
public class GraphApiUserExample{
#JsonProperty("objectId")
private String id;
private Boolean accountEnabled;
private PasswordProfile PasswordProfile;
private List<SignInName> signInNames;
private String surname;
private String displayName;
private String givenName;
#JsonProperty("userPrincipalName")
private String userPrincipalName;
public String getId(){
return id;
}
public void setId(final String id){
this.id = id;
}
public Boolean getAccountEnabled(){
return accountEnabled;
}
public void setAccountEnabled(final Boolean accountEnabled){
this.accountEnabled = accountEnabled;
}
public PasswordProfile getPasswordProfile(){
return passwordProfile;
}
public void setPasswordProfile(final PasswordProfile passwordProfile){
this.passwordProfile = passwordProfile;
}
public List<SignInName> getSignInNames(){
return signInNames;
}
public void setSignInNames(final List<SignInName> signInNames){
this.signInNames = signInNames;
}
public String getSurname(){
return surname;
}
public void setSurname(final String surname){
this.surname = surname;
}
public String getDisplayName(){
return displayName;
}
public void setDisplayName(final String displayName){
this.displayName = displayName;
}
public String getGivenName(){
return givenName;
}
public void setGivenName(final String givenName){
this.givenName = givenName;
}
public String getUserPrincipalName(){
return userPrincipalName;
}
public void setUserPrincipalName(final String userPrincipalName){
this.userPrincipalName = userPrincipalName;
}
#JsonIgnore
public String getSignInEmail(){
String email = "";
if(signInNames != null){
for(SignInName signInName : signInNames){
if(signInName.getType().equals("emailAddress")){
email = signInName.getValue();
break;
}
}
}
return email;
}
#JsonIgnore
public void setSignInEmail(String signInEmail){
if(signInNames == null){
signInNames = new ArrayList<>();
signInNames.add(new SignInName("emailAddress", signInEmail));
return;
}
for(SignInName signInName : signInNames){
if(signInName.getType().equals("emailAddress")){
signInName.setValue(signInEmail);
break;
}
}
}
}
SignInName:
public class SignInName {//userName or emailAddress
private String
type,
value;
public String getType(){
return type;
}
public void setType(final String type){
this.type = type;
}
public String getValue(){
return value;
}
public void setValue(final String value){
this.value = value;
}
}
PasswordProfile:
#JsonIgnoreProperties(ignoreUnknown = true)
public class PasswordProfile {
private String password;
private Boolean forceChangePasswordNextLogin;
public String getPassword(){
return password;
}
public void setPassword(final String password){
this.password = password;
}
public Boolean getForceChangePasswordNextLogin(){
return forceChangePasswordNextLogin;
}
public void setForceChangePasswordNextLogin(final Boolean forceChangePasswordNextLogin){
this.forceChangePasswordNextLogin = forceChangePasswordNextLogin;
}
}

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);
}
}

GSON fromJSON having problems

I have a POJO class as below.
import java.util.List;
public class LocationInfoDTO{
private int _id;
private String name;
private String type;
private String fullName;
private int location_id;
private boolean isEurope;
private String countryCode;
private boolean coreCountry;
private int iataAirportCode;
private List<Geospatial> geo_location;
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public int getLocation_id() {
return location_id;
}
public void setLocation_id(int location_id) {
this.location_id = location_id;
}
public boolean isEurope() {
return isEurope;
}
public void setEurope(boolean isEurope) {
this.isEurope = isEurope;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public boolean isCoreCountry() {
return coreCountry;
}
public void setCoreCountry(boolean coreCountry) {
this.coreCountry = coreCountry;
}
public int getIataAirportCode() {
return iataAirportCode;
}
public void getIataAirportCode(int iataAirportCode) {
this.iataAirportCode = iataAirportCode;
}
#Override
public String toString() {
return "LocationInfoDTO [_id=" + _id + ", name=" + name + ", type="
+ type + ", fullName=" + fullName + ", location_id="
+ location_id + ", isEurope=" + isEurope + ", countryCode="
+ countryCode + ", coreCountry=" + coreCountry
+ ", iataAirportCode=" + iataAirportCode + ", geo_location="
+ geo_location + "]";
}
public List<Geospatial> getGeo_location() {
return geo_location;
}
public void setGeo_location(List<Geospatial> geo_location) {
this.geo_location = geo_location;
}
}
All there will be inside a JSON object, just one thing the geospatial attribute has latitude and longitude and that is a different POJO class.All happens good using GSON fromJSON except the geo-location thing is null;
{"_id":376217,"key":null,"name":"test","fullName":"test, test","geo_position":{"latitude":52.52437,"longitude":13.41053}}
This is a sample JSON.
Triggering in this way
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JSONArray array = new JSONArray(json);
for(int i=0;i<array.length();i++){
System.out.println("Array:"+gson.fromJson(array.getJSONObject(i).toString(), LocationInfoDTO.class));
EDIT--------------------------------
Changed the geo-location to geo-position
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
The error says exaclty what's wrong. You have a json object there for geo-location and it expects a list. Even if it's a one element list. Change
{"_id":376217,"key":null,"name":"test","fullName":"test, test","geo_position":{"latitude":52.52437,"longitude":13.41053}}
to
{"_id":376217,"key":null,"name":"test","fullName":"test, test","geo_position":[{"latitude":52.52437,"longitude":13.41053}]}
UPDATE
Since there will always be one lat/long, you should update your POJO so that geo_location is a single GeoSpatial object, not a List<GeoSpatial>

All errors not added to PageMessages

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;

Resources