• Jesus G
  • NEWBIE
  • 45 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 22
    Replies
Hello!

I would need to calculate the difference between 2 dates in years, months and days, and considering the difficulty to have a precise value by using the available functions and classes, I wondered if it would be possible to get the result by using moment.js.

The idea is to have 2 custom date fields and use moment.js to determine the difference between them in a format similar to 'x Years, x Months and x Days' when any of the values change.

Many thanks!
Jesus
Hello!

Please, could you help me to write the part of a test class for covering the following code? I have tried by updating a record without LastName to generate an error but still the Database.Error line is not being covered.
 
System.debug('Verification of number of Leads to be updated: ' + listOfLeads.size());
Database.SaveResult[] srLeadList = Database.update(listOfLeads, false);
for (Database.SaveResult sr : srLeadList) {
     if (sr.isSuccess()) {
          // Operation was successful, so get the ID of the record that was processed
          System.debug('Lead record successfully updated: ' + sr.getId());
     }
     else {
        // Operation failed, so get all errors                
        	for(Database.Error err : sr.getErrors()) {
            	System.debug('The following error has occurred.');                    
            	System.debug(err.getStatusCode() + ': ' + err.getMessage());
            	System.debug('Lead fields that affected this error: ' + err.getFields());
        	}
     }
}

Thank you very much!
J

 
Hello!

Please, could you help me to write the test class for this code where I am using the SandboxPostCopy interface to modify an account field after refreshing a sandbox? I have tried by creating a test class that updates Account records but the code coverage is 0...
global class AfterSandboxRefresh implements SandboxPostCopy {
	global void runApexClass(SandboxContext context) {

	List<Account> listOfAccounts = new List<Account>();

	List<Account> accountsToUpdate = [SELECT Id, Email__c
									  FROM Account
									  WHERE Email__c != NULL AND Email__c Like '%_@__%.__%'];

	if(!accountsToUpdate.isEmpty()) { 
		For (Account acc : accountsToUpdate) {
			Email__c = Email__c + '.noemail';
			listOfAccounts.add(acc);            
		}
	Database.Update(listOfAccounts, false);
	}
	}
}

Thank you very much!
J
Hello,

I am preparing a class that will be automatically executed after having a sandbox refreshed and I wondered how I could call a future method that is part of a different class which already determines the records that need to be updated.
public class AfterSandboxRefreshAuxiliar {
    @future
    public static void updateUsersAfterRefresh () { 
		List <User> listofUsers = new List<User>();
		List <User> usersToUpdate = [SELECT Id,email
        	                      	FROM User
            	               		WHERE Profile.Name = 'System Administrator'];
        For (User u : usersToUpdate) {
            u.email = u.email.replace ('noemail', '');
			listofUsers.add(u);            
        }
        update listofUsers;
	}
}

I cannot use something like the following code so, any ideas, please?
AfterSandboxRefreshAuxiliar.updateUsersAfterRefresh();

Many thanks!
J
Hello,

I am writing a class for the User object where I have 2 lists that collect the new and old values of the trigger. Would it be possible to compare the 2 values of the same record and perform an action only if it has changed? Please, notice I am not using Maps since the future annotation is needed:
 
@future
    public static void handleAfterUpdate(Set<Id> newUserIds, Set<Id> oldUserIds) { 
        List <Contact> contactsToUpdate = new List <Contact>();
        List<User> newUsersList = [SELECT Id, ContactId, Profile.Name, Username, IsActive FROM User WHERE Id IN :newUserIds];
		List<User> oldUsersList = [SELECT Id, ContactId, Profile.Name, Username, IsActive FROM User WHERE Id IN :oldUserIds];
        for (User currentUser : /* list of the records where the previous fields have changed */) {
        	Contact con = new Contact();
            con.Id = currentUser.ContactId;
            con.User_profile__c = currentUser.Profile.Name;
            con.User_username__c = currentUser.Username;
            con.Active_User__c = currentUser.IsActive;
            contactsToUpdate.add(con);
        }
        update contactsToUpdate;
    }

Thank you very much,
J
Hello!

Please, could you help me to edit the following class so I can use it to compare old and new values when using it in an After Update trigger? It is working as expected for an After Insert trigger, but I would need it to compare old and new values so only the records whose fields changes are updated. I understand I need to use Map instead of Set but I cannot see how for the User object.

Trigger:
trigger AllUserTriggers on User (after insert, after update) {
    if(Trigger.isAfter && Trigger.isInsert) {
            AllUserTriggersHandler.handleAfterInsert(Trigger.newMap.keySet());
    }
    if(Trigger.isAfter && Trigger.isUpdate) {
            AllUserTriggersHandler.handleAfterUpdate(Trigger.newMap.keySet());
    }
}

Class:
public class AllUserTriggersHandler {
    @future
    public static void handleAfterUpdate(Set<Id> UserIds) { 
        List <Contact> contactsToUpdate = new List <Contact>();
        List<User> userList = [SELECT Id, ContactId, Profile.Name, Username, IsActive FROM User WHERE Id IN :UserIds];
        for (User currentUser : userList) {
            if (currentUser.ContactId != null){
        		Contact con = new Contact();
                con.Id = currentUser.ContactId;
                con.User_profile__c = currentUser.Profile.Name;
                con.User_username__c = currentUser.Username;
                con.Active_User__c = currentUser.IsActive;
                contactsToUpdate.add(con);
            }
        }
        update contactsToUpdate;
    }
}
Thank you very much!
Jesus
Hello,

Please, could you help me to edit the following class so instead of updating the 'Total_Hours__c' Account field with the number of related Cases, it is updated with the sum of the 'Hours__c' field of its related Cases?
public class CasesTriggerHandler {
    public static void handleAfterInsert(List<Case> CasesList){
        Set<Id> setAccountIds = new Set<Id>();
    	List <Account> AccountsToUpdate = new List <Account>();
        
        for (Case currentCase : CasesList) {
                setAccountIds.add(currentCase.AccountId);
        }
        
		Map<Id, Account> AccountMap = new Map<Id, Account> ([SELECT Id, Total_Hours__c FROM Account WHERE Id IN: setAccountIds]);
        
        for (Account currentAccount : [SELECT Id,Total_Hours__c, (SELECT Id FROM Cases) FROM Account WHERE Id IN : setAccountIds]){
			AccountMap.get(currentAccount.Id).Total_Hours__c = currentAccount.Cases.size();
            AccountsToUpdate.add(AccountMap.get(currentAccount.Id));
		}
        update AccountsToUpdate;
    }
}
Many thanks!
J
Hello,

Please, could you help me to determine which is the issue in this code? I am trying to update a list of records related (through a lookup field) to the object which is being modified.
 
public class HandlerResources {
    public static void handleAfterInsert(List<Resource__c> ResourceList) { 
        List <Project__c> ProjectsToUpdate = new List<Project__c>();
            for (Resource__c currentResource : ResourceList) {
                if (currentResource.Project__c != '') {
                    for (Project__c Project : currentResource.Project__c.Id) {
                    Project.Hours__c = Project.Hours__c + currentResource.Hours__c;
                	ProjectsToUpdate.add(Project);
                    }
                }
            }
        Database.update(ProjectsToUpdate);
    }
}

Thank you very much!
Jesus
Hello,

With the help of this post (http://bobbuzzard.blogspot.co.uk/2011/07/managing-list-of-new-records-in.html), I have created a Controller and a VF page to insert in bulk several Contacts. I have created a custom button on the Account object where the VF page is called but I would like to know how to populate the Account Id (from which the button is clicked) to the 'Account' lookup field of the contact in the VF page.

Thank you very much!
J
Hello!

As part of the Challenage proposed for the 'Getting Started with Apex' trailhead topic, I am tryting the following:
Create an Apex class that returns an array (or list) of formatted strings ('Test 0', 'Test 1', ...). The length of the array is determined by an integer parameter. 
The Apex class must be called 'StringArrayTest' and be in the public scope.
The Apex class must have a public static method called 'generateStringArray'.
The 'generateStringArray' method must return an array (or list) of strings. Each string must have a value in the format 'Test n' where n is the index of the current string in the array. The number of returned strings is specified by the integer parameter to the 'generateStringArray' method.

If I create a class just with the first 3 lines of the following code and execute the rest in an anonymous windows, it works as expected. However, could I have everything just in one class?

public class StringArrayTest {
    public static Integer generateStringArray = 10;
}
        for(Integer i=0;i<StringArrayTest.generateStringArray;i++) {
            System.debug('Test '+ i);
        }

Many thanks!
Jesus
Hello!

I would need to calculate the difference between 2 dates in years, months and days, and considering the difficulty to have a precise value by using the available functions and classes, I wondered if it would be possible to get the result by using moment.js.

The idea is to have 2 custom date fields and use moment.js to determine the difference between them in a format similar to 'x Years, x Months and x Days' when any of the values change.

Many thanks!
Jesus
Hello!

Please, could you help me to write the part of a test class for covering the following code? I have tried by updating a record without LastName to generate an error but still the Database.Error line is not being covered.
 
System.debug('Verification of number of Leads to be updated: ' + listOfLeads.size());
Database.SaveResult[] srLeadList = Database.update(listOfLeads, false);
for (Database.SaveResult sr : srLeadList) {
     if (sr.isSuccess()) {
          // Operation was successful, so get the ID of the record that was processed
          System.debug('Lead record successfully updated: ' + sr.getId());
     }
     else {
        // Operation failed, so get all errors                
        	for(Database.Error err : sr.getErrors()) {
            	System.debug('The following error has occurred.');                    
            	System.debug(err.getStatusCode() + ': ' + err.getMessage());
            	System.debug('Lead fields that affected this error: ' + err.getFields());
        	}
     }
}

Thank you very much!
J

 
Hello!

Please, could you help me to write the test class for this code where I am using the SandboxPostCopy interface to modify an account field after refreshing a sandbox? I have tried by creating a test class that updates Account records but the code coverage is 0...
global class AfterSandboxRefresh implements SandboxPostCopy {
	global void runApexClass(SandboxContext context) {

	List<Account> listOfAccounts = new List<Account>();

	List<Account> accountsToUpdate = [SELECT Id, Email__c
									  FROM Account
									  WHERE Email__c != NULL AND Email__c Like '%_@__%.__%'];

	if(!accountsToUpdate.isEmpty()) { 
		For (Account acc : accountsToUpdate) {
			Email__c = Email__c + '.noemail';
			listOfAccounts.add(acc);            
		}
	Database.Update(listOfAccounts, false);
	}
	}
}

Thank you very much!
J
Hello,

I am preparing a class that will be automatically executed after having a sandbox refreshed and I wondered how I could call a future method that is part of a different class which already determines the records that need to be updated.
public class AfterSandboxRefreshAuxiliar {
    @future
    public static void updateUsersAfterRefresh () { 
		List <User> listofUsers = new List<User>();
		List <User> usersToUpdate = [SELECT Id,email
        	                      	FROM User
            	               		WHERE Profile.Name = 'System Administrator'];
        For (User u : usersToUpdate) {
            u.email = u.email.replace ('noemail', '');
			listofUsers.add(u);            
        }
        update listofUsers;
	}
}

I cannot use something like the following code so, any ideas, please?
AfterSandboxRefreshAuxiliar.updateUsersAfterRefresh();

Many thanks!
J
Hello,

I am writing a class for the User object where I have 2 lists that collect the new and old values of the trigger. Would it be possible to compare the 2 values of the same record and perform an action only if it has changed? Please, notice I am not using Maps since the future annotation is needed:
 
@future
    public static void handleAfterUpdate(Set<Id> newUserIds, Set<Id> oldUserIds) { 
        List <Contact> contactsToUpdate = new List <Contact>();
        List<User> newUsersList = [SELECT Id, ContactId, Profile.Name, Username, IsActive FROM User WHERE Id IN :newUserIds];
		List<User> oldUsersList = [SELECT Id, ContactId, Profile.Name, Username, IsActive FROM User WHERE Id IN :oldUserIds];
        for (User currentUser : /* list of the records where the previous fields have changed */) {
        	Contact con = new Contact();
            con.Id = currentUser.ContactId;
            con.User_profile__c = currentUser.Profile.Name;
            con.User_username__c = currentUser.Username;
            con.Active_User__c = currentUser.IsActive;
            contactsToUpdate.add(con);
        }
        update contactsToUpdate;
    }

Thank you very much,
J
Hello!

Please, could you help me to edit the following class so I can use it to compare old and new values when using it in an After Update trigger? It is working as expected for an After Insert trigger, but I would need it to compare old and new values so only the records whose fields changes are updated. I understand I need to use Map instead of Set but I cannot see how for the User object.

Trigger:
trigger AllUserTriggers on User (after insert, after update) {
    if(Trigger.isAfter && Trigger.isInsert) {
            AllUserTriggersHandler.handleAfterInsert(Trigger.newMap.keySet());
    }
    if(Trigger.isAfter && Trigger.isUpdate) {
            AllUserTriggersHandler.handleAfterUpdate(Trigger.newMap.keySet());
    }
}

Class:
public class AllUserTriggersHandler {
    @future
    public static void handleAfterUpdate(Set<Id> UserIds) { 
        List <Contact> contactsToUpdate = new List <Contact>();
        List<User> userList = [SELECT Id, ContactId, Profile.Name, Username, IsActive FROM User WHERE Id IN :UserIds];
        for (User currentUser : userList) {
            if (currentUser.ContactId != null){
        		Contact con = new Contact();
                con.Id = currentUser.ContactId;
                con.User_profile__c = currentUser.Profile.Name;
                con.User_username__c = currentUser.Username;
                con.Active_User__c = currentUser.IsActive;
                contactsToUpdate.add(con);
            }
        }
        update contactsToUpdate;
    }
}
Thank you very much!
Jesus
Hello,

Please, could you help me to edit the following class so instead of updating the 'Total_Hours__c' Account field with the number of related Cases, it is updated with the sum of the 'Hours__c' field of its related Cases?
public class CasesTriggerHandler {
    public static void handleAfterInsert(List<Case> CasesList){
        Set<Id> setAccountIds = new Set<Id>();
    	List <Account> AccountsToUpdate = new List <Account>();
        
        for (Case currentCase : CasesList) {
                setAccountIds.add(currentCase.AccountId);
        }
        
		Map<Id, Account> AccountMap = new Map<Id, Account> ([SELECT Id, Total_Hours__c FROM Account WHERE Id IN: setAccountIds]);
        
        for (Account currentAccount : [SELECT Id,Total_Hours__c, (SELECT Id FROM Cases) FROM Account WHERE Id IN : setAccountIds]){
			AccountMap.get(currentAccount.Id).Total_Hours__c = currentAccount.Cases.size();
            AccountsToUpdate.add(AccountMap.get(currentAccount.Id));
		}
        update AccountsToUpdate;
    }
}
Many thanks!
J
Hello,

Please, could you help me to determine which is the issue in this code? I am trying to update a list of records related (through a lookup field) to the object which is being modified.
 
public class HandlerResources {
    public static void handleAfterInsert(List<Resource__c> ResourceList) { 
        List <Project__c> ProjectsToUpdate = new List<Project__c>();
            for (Resource__c currentResource : ResourceList) {
                if (currentResource.Project__c != '') {
                    for (Project__c Project : currentResource.Project__c.Id) {
                    Project.Hours__c = Project.Hours__c + currentResource.Hours__c;
                	ProjectsToUpdate.add(Project);
                    }
                }
            }
        Database.update(ProjectsToUpdate);
    }
}

Thank you very much!
Jesus
Hello,

With the help of this post (http://bobbuzzard.blogspot.co.uk/2011/07/managing-list-of-new-records-in.html), I have created a Controller and a VF page to insert in bulk several Contacts. I have created a custom button on the Account object where the VF page is called but I would like to know how to populate the Account Id (from which the button is clicked) to the 'Account' lookup field of the contact in the VF page.

Thank you very much!
J