• Glyn Anderson 3
  • SMARTIE
  • 1244 Points
  • Member since 2017

  • Chatter
    Feed
  • 37
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 253
    Replies
On https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_expressions_operators_understanding.htm
it is stated that:

"Unlike Java, == in Apex compares object value equality, not reference equality, except for user-defined types."
"For sObjects and sObject arrays, == performs a deep check of all sObject field values before returning its result. Likewise for collections and built-in Apex objects." 

Why are the two asserts below failing then? If you look at the debug logs with the "Debug Only" option selected you should see that all 3 objects re identical.

Are the asserts below failing for you as well or is it just a glitch in my dev org?

// Two different ways to get a DescribeSObjectResult object 
        DescribeSObjectResult dsor1 = Account.SObjectType.getDescribe();
        DescribeSObjectResult dsor2 = Schema.sObjectType.Account;
        
        // Another way to get the DescribeSObjectResult using the Schema object
        List<DescribeSObjectResult> l =  Schema.describeSObjects(new List<String> {'Account'});
        DescribeSObjectResult dsor3 = l[0];
        
        System.assert(dsor1 == dsor2); // succeeds
       //System.assert(dsor1 == dsor3); // fails
      // System.assert(dsor2 == dsor3); // fails
       System.assert(dsor1.getsObjectType() == dsor3.getsObjectType()); // succeeds
       System.assert(dsor2.getsObjectType() == dsor3.getsObjectType()); // succeeds
        
        // If you look at the debug logs with the "Debug Only" option selected
        // you should see that the objects below are identical
        system.debug('dsor1: ' + dsor1);
        system.debug('dsor2: ' + dsor2);
        system.debug('dsor3: ' + dsor3);

 
  • March 13, 2018
  • Like
  • 0
I have the following very simple VF page to display two dependent picklists (3 tiers total) using a custom controller. When I attempt to save the VF page, I get the error message above.
In the developer console, I see two Problems at Line 0. 1) ABS_Services_Input, Unknown property 'String.Services__c and 2) "Duplicate value found: duplicates value on record with id:" (Yes, literally. No id # given.)

<apex:page controller="ABSServicesController">
    <apex:messages style="color:red"></apex:messages>  
    <apex:form >
        <apex:pageBlock title="Dependent Picklist Entry">
            <apex:repeat value="{!serviceList}" var="svcItem">
                <apex:pageBlockSection title="{!svcItem.Services__c}" columns="1">
                    <apex:pageBlockSection title="{!svcItem.Capabilities__c}" columns="1">
                        <apex:pageBlockSection title="{!svcItem.Sub_Capabilities__c}" columns="1">
                        </apex:pageBlockSection>
                    </apex:pageBlockSection>
                </apex:pageBlockSection>
            </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page> 

This is my Custom Controller code:

public with sharing class ABCServicesController{

    public String serviceList { get; set; }
 
    public List<ServiceOffered__c> servicesList{get;set;}
    public Map<String, Map<String, List<String>>> serviceMap{get;set;}
    
    public ABCservicesController(){
        serviceMap = new Map<String, Map<String, List<String>>>();
        
        servicesList = [Select ID, Services__c, Capabilities__c, Sub_Capabilities__c From ServiceOffered__c];
        
        for(ServiceOffered__c svcItem : servicesList) {
            if(serviceMap.containsKey(svcItem.Services__c)) {
                if(serviceMap.get(svcItem.Services__c).containsKey(svcItem.Capabilities__c)) {
                    serviceMap.get(svcItem.Services__c).get(svcItem.Capabilities__c).add(svcItem.Sub_Capabilities__c);
                } else {                    
                    serviceMap.get(svcItem.Services__c).put(svcItem.Capabilities__c, new List<String>{svcItem.Sub_Capabilities__c});
                }
            } else {
                Map<String, List<String>> m = new Map<String, List<String>>();
                m.put(svcItem.Capabilities__c, new List<String>{svcItem.Sub_Capabilities__c});
                serviceMap.put(svcItem.Services__c, m);
                //new Map<String, List<String>>{svcItem.Capabilities__c : new List<String>{svcItem.Capabilities__c}}
            }
        }
    }     
}

I do not know if it is relevant but earlier I was getting an unknow property error serviceList related to the line "Public List<ServiceOffered__c> serviceList{get;set;}".  
My path toward resolution, besides asking all of you great folks, is to figure out why the variable svcItem was expected to be something other than a string when every service being pulled into the List is a string.
Thanks in advance,
Wade
Hi,
i am getting a post call out from external stsyem. i am creating or updating a  custom object record out of it. Can anyone please let em know how to write a test classs for it?
Here is my code:

global without sharing class ContactService {
    
    @HttpPost
    global static String insertContact(ContactInfoParser contactRec){
        //creation or update of application record. Mapping the fields from ContactInfoParser class.
        String RecordTypeApplicationId = Schema.SObjectType.Application__c.getRecordTypeInfosByName().get('Test').getRecordTypeId();        
        Application__c applicationObj = new Application__c();
        applicationObj.Id = contactRec.application.applicationId;
        applicationObj.applicant__c = contactRec.contact.contactId;
        applicationObj.RecordTypeId = RecordTypeApplicationId;
        applicationObj.assessPriorLearning__c = contactRec.application.assessPriorLearning;
        applicationObj.Status__c = contactRec.application.status;
        applicationObj.reason__c= contactRec.application.reason;
        applicationObj.priorLearningNotes__c= contactRec.application.priorLearningNotes;
        applicationObj.applingForCredit__c= contactRec.application.applingForCredit;
        upsert applicationObj;


Thanks
  • March 09, 2018
  • Like
  • 0
Hello all,

I am trying to write a batch class (MY FIRST EVER), to take in the AsyncApexJob object and create a csv file of the errors and send to an email address.  I'm sure that some of my syntax is not correct (I would appreciate any input), but I can't even execute to see if it works.  I am receiving the above message when I open a second anonymous window and enter:

AriaBatchErrors objClass=new AriaBatchErrors();
Database.executeBatch(objClass);


So that I can execute:

global class AriaBatchErrors implements Database.Batchable<Sobject>
{
    global string[] email=new String[] {'myEmail@address.com'};
    string[] Lines;
    //start method
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        lines = new String[0];
        return Database.getQueryLocator('SELECT Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE NumberOfErrors > 0');

    }

    //execute
    global void execute(Database.BatchableContext BC, List<String> scope)
    {
        // process
           for(String record: scope) 
        {
        String line = '';
        // header row
        if ( lines.size() == 0 ) {
            line = 'ID, Status, Number of Errors, Job Items Processed, Total Job Items, Created By';
            lines.add(line);
        }
        else {
            // build csv lines here
            line +='"' + record.get('Id')  +'"'
            +',' + '"' + record.get('Status') + '"'
            +',' + '"' + record.get('NumberOfErrors') +'"'
            +',' + '"' + record.get('JobItemsProcessed') + '"'
            +',' + '"' + record.get('TotalJobItems') + '"' 
            +',' + '"' + record.get('CreatedBy.Email') + '"'   ;               
            lines.add(line);

            system.debug('Line No >>> ' + line); 
        }
         }  // end of for loop   
        
    }


    //finish
    global void finish (Database.BatchableContext BC)
    {
        Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
        AsyncApexJob a =[select a.TotalJobItems,a.Status,a.NumberOfErrors,a.JobItemsProcessed,a.ExtendedStatus,a.createdById,a.completedDate from AsynchApexJob];
        System.debug('Job Id')+BC.getJobId());
        mail.ToAddreses(email);
        mail.setSenderDisplayName('Apex Batch Processing Errors');
        mail.setSubject('Batch Errors');
        mail.setPlainTextBody('This will be the body of the email' + a.TotalJobItems + 'batches with '+ a.NumberOfErrors);
    }
}

Please help, I am so so new. 

Timothy
Dear Developer Community,

I have a case where i need to create an auto complete milestone on case. I took example from this documentation http://resources.docs.salesforce.com/latest/latest/en-us/sfdc/pdf/salesforce_entitlements_implementation_guide.pdf page 29 - 33. Everything is fine but then problem occured when the test unit provided in the guide only cover 50% of its util class.

I found this exact same question on the stackexchange https://salesforce.stackexchange.com/questions/141607/57-code-coverage-on-milestone-complete/141624 but still I'm confused on how to implement it in code

I'm breaking my head to solve this, please help. Any kind will be very appreciated
Hi,

I am trying to unarchive a record in Salesforce. I found two solutions online, but I don't understand the steps to take in order to unarchive the record.

Solution #1 Source: https://salesforce.stackexchange.com/questions/70860/how-to-unarchive-activities

Use queryAll in the API to retrieve the activities, then perform an update to the records. You only need to call update() using just records by Id value (you just "touch" the record). They will be restored upon saving.
The Data Loader exposes queryAll as "Export All."

OR

Solution #2 Source: https://help.salesforce.com/articleView?id=000199524&type=1

1.) Use Workbench or use any tool and select the option include Deleted and Archived records,which could use queryAll() method. The queryAll() method needs a connection setup as it can only be used via an API call. 
 2.) ALL ROWS is only intended for use in Apex SOQL queries. The documentation for ALL ROWS is in the Apex code documentation. The equivalent of ALL ROWS in the API is to call queryAll() instead of query(). You can't use that in Developer Console's Query Editor as the query editor doesn't execute it as Apex Code,it executes directly as a REST query API call.
3.) Salesforce Support can increase the archive period for your ORG, to retrieve more archived records.

Can you show images in how to solve this?
QueryAll() -- Am i supposed to put something in the ()?
Update() -- Again, do I put something in the ()?

Thank you very much for your help. I can't uninstall a specific package until this is fixed.
Hi all can you please help me on this:
I am getting the above error 
List<req> reqlist = new List<req>();        
        set<Id> accountIds = new set<Id>();        
        
        for (opp op : opps) {
              accountIds.add(op.AccountId);
        }
        
        List<req> ExReq = new List<req>([Select Id, Type__c, Account__c, opp__c,stat__c,Opp__r.Is_Upd__c FROM req Where Account__c =:accountIds                                  
                                    AND Opportunity__c IN:opps AND Type__c = 'XYZ']);
        
        List<req> reqcan = new List<req>
        Integer reqIndex = 0;
        
        for(req req : ExReq){
            if(req.Opp__r.Is_Upd__c == true){
                req.stat__c = 'Cancelled';
                reqcan.add(req);
                ExReq.remove(reqIndex);
            }
            reqIndex = reqIndex + 1 ;
        }
        
        if(!reqcan.isEmpty()){
            update reqcan ;
        }
I would like to great everyone there. This is my very first post in this forum. I am facing a real problem. I am responsible for developing on Salesforce for an NGO and begin using Salesforce for 8 months. So I am realy new.

I have learned about the system limitations, such as governor limits. Apex best practice, avoid SOQL queries or DMl code in for/while loop.

So, I try to do my best. but, I am facing a real probleme that I have to explain a litle bit. For an NGO, it is import to report monthly to the donors. It comes to my boss this idea to automatically generate indicators values as the projects progress. as a matter of fact, every single time a user insert/update/delete a record, the related indicator must be update. so far, so good. the problem comes when we consider that the organization produces a very high quantity of informations. so, it's impossible to insert then one by oneusing forms. So we need to implement mass Edit/update or import with CSV file. Which is good. There is alot of indicators, so, when an action trigger on an object, it is very important that the related indicator be created or updated for the precise month. Thus, I use the following code 

A) Utility Class I use to handle some functions that I need for all trigger handlers
public class UtilitiesRecordTrack {
	   
   Public static double getPercent(integer numerateur, integer denominateur)
   {
       return (double) denominateur > 0 ? (( (double) numerateur / (double) denominateur ) * 100) : 0;
   }
    
   public static ID getProjectID(String projectName)
    {
        ID projectId = [SELECT Id FROM Project_1__c WHERE Name = : projectName].Id;
        return projectId;
    }
    
    public static List<Indicator_1__c> getIndicator(String indicatorFullName, String projectName)
    {
        Indicator_1__c[] indicator = [SELECT Id, Indicator_Full_Name__c, Related_Project__c
                                                 FROM Indicator_1__c 
                                                 WHERE Indicator_Full_Name__c =: indicatorFullName
                                                 AND Related_Project__c =: getProjectID(projectName)
                                     ];
        return indicator;
    }
    
    public static List<Track_Indicator__c> getTrackIndicatorId(ID indicatorId, Decimal monthNumber, ID operationId)
    {
        return [SELECT Id FROM Track_Indicator__c WHERE Indicator_Id__c = 
                                                  :indicatorId
                                                   AND Month_Number__c = : monthNumber 
                                                   AND Operation_Name__c = : operationId]; 
    }
    
    public static List<Track_Indicator__c> getTrackIndicatorId(String indicatorFullName, Decimal monthNumber, ID operationId, String projectName)
    {
        return [SELECT Id, Indicator_Id__r.Indicator_Full_Name__c, Indicator_Id__r.Related_Project__c, Indicator_Id__c FROM Track_Indicator__c
                                                   WHERE Indicator_Id__r.Indicator_Full_Name__c = :indicatorFullName
                                                   AND Indicator_Id__r.Related_Project__c = :[SELECT Id FROM Project_1__c WHERE Name =:projectName]
                                                   AND Month_Number__c = : monthNumber 
                                                   AND Operation_Name__c = : operationId]; 
    }

    public static void recordOrUpdate(List<Track_Indicator__c> trackToUpdate, Decimal actual, Date d, ID i, ID o)
    {
            System.debug('Function clalled');
           if(trackToUpdate.size() > 0)
           {
              trackToUpdate[0].Actual__c = actual;
              trackToUpdate[0].Date__c =  d;
              update trackToUpdate;
              System.debug('Updated');
            }else{
                 Track_Indicator__c newTrack = new Track_Indicator__c();
                 newTrack.Actual__c = actual;
                 newTrack.Date__c = d;
                 newTrack.Indicator_Id__c = i;
                 newTrack.Operation_Name__c = o;
                 insert newTrack;
                 System.debug('Inserted');
             }
     }
    
    public static void UpdateTrack(Track_Indicator__c trackToUpdate, Decimal actual, Date d, ID o)
    {
       trackToUpdate.Actual__c = actual;
       trackToUpdate.Date__c =  d;
       trackToUpdate.Operation_Name__c = o;
       update trackToUpdate;
       System.debug('Updated');
    }
    
     public static void TrackCreate(Decimal actual, Date d, ID i, ID o){
       Track_Indicator__c t = new Track_Indicator__c();
        t.Actual__c = actual;
        t.Date__c = d;
        t.Indicator_Id__c = i;
        t.Operation_Name__c = o;
        insert t;
    }
}


This is a trigger handler class
 
public class RecordTrackOnSongHelper {
    public static double getTotalSongWrintenByschool(Decimal month , ID operation)
    {
        return [SELECT Id FROM Song__c WHERE Month_Number__c = :month AND Operation_Name__c = :operation].size();
    }
    
    public static void recordTrack(List<Song__c> newRecords, String indicatorFullName, String projectName){
        
      
        if(indicatorFullName == '# of songs written by participating schools'
                                && projectName == 'Music Heals International')
        {
             //List<Track_Indicator__c> trackToInsertCaseStudy = new List<Track_Indicator__c>() ;
             //List<Track_Indicator__c> trackToUpdateCaseStudy = new List<Track_Indicator__c>() ;
             Indicator_1__c[] indicator = UtilitiesRecordTrack.getIndicator(indicatorFullName, projectName);
             if(indicator.size() > 0)
             {
                 Decimal actual;
                 for(Song__c s : newRecords)
                 {
                         actual = (Decimal) getTotalSongWrintenByschool(s.Month_Number__c , s.Operation_Name__c);
                         Track_Indicator__c[] tracked =  UtilitiesRecordTrack.getTrackIndicatorId(indicator[0].Id, s.Month_Number__c, s.Operation_Name__c);
                         UtilitiesRecordTrack.recordOrUpdate(tracked, actual, s.Date__c, Indicator[0].Id, s.Operation_Name__c);
                 }

             }
        }

    }
}

But see it for activities:
 
public class RecordTrackOnActivityHelper {
    
    public static double  getTotalActivityOn(Decimal month, ID operation, String activityType, ID projectId)
    {
          return [SELECT Id FROM Activity_1__c WHERE 
                                               Activity_Type__c = :activityType
                                               AND Project_Name__c =:projectId
                                               AND Month_Number__c =: month
                                               AND Operation_Name__c =: operation].size();
    }
    
    public static double getTotalCommunityMemberSensitized(Decimal month, ID operation, String activityType, ID project)
    {
        return double.valueOf([SELECT SUM(Number_Of_Participant__c) FROM Activity_1__c
                                                     WHERE Activity_Type__c = :activityType
                                                     AND Month_Number__c =: month
                                                     AND Project_Name__c = : project
                                                     ANd Operation_Name__c =: operation][0].get('expr0'));
    }
    
    public static double getTotalTotalConertHeledBy(Decimal month, ID operation, String activityType, ID pr){
        return [SELECT Id FROM Activity_1__c WHERE Activity_Type__c =:activityType
                                             AND Month_Number__c = :month
                                             AND Project_Name__c = : pr
                                             AND Operation_Name__c =: operation
               ].size();
    }
    
    
    public static Double getTotalBoys(Decimal month, ID op, String actType, ID pr){
       return double.valueOf([SELECT SUM(Number_Of_Male_Participant__c) FROM Activity_1__c
                                                     WHERE Activity_Type__c = : actType
                                                     AND Month_Number__c =: month
                                                     AND Project_Name__c = : pr
                                                     ANd Operation_Name__c =: op ][0].get('expr0'));
    }
    
    
    public static Double getTotalGirls(Decimal month, ID op, String actType, ID pr){
       return double.valueOf([SELECT SUM(Number_Of_Female_Participant__c) FROM Activity_1__c
                                                     WHERE Activity_Type__c = :actType
                                                     AND Month_Number__c =: month
                                                     AND Project_Name__c = : pr
                                                     ANd Operation_Name__c =: op ][0].get('expr0'));
    }
    
    
 
    public static void recordTrack(List<Activity_1__c> newRecords, String indicatorFullName, String projectName){
        
              
        if(indicatorFullName == 'Number  extracurricular activities'
                                && projectName == 'School Of Hope')
        {
             Indicator_1__c[] indicator = UtilitiesRecordTrack.getIndicator(indicatorFullName, projectName);
             if(indicator.size() > 0)
             {
                 Decimal actual;
                 for(Activity_1__c act : newRecords)
                 {
                     if(act.Activity_Type__c == 'Extra Curricula Activity'
                        && act.Project_Name__c == UtilitiesRecordTrack.getProjectID(projectName))
                     {
                         actual = (Decimal) getTotalActivityOn(act.Month_Number__c, act.Operation_Name__c, act.Activity_Type__c, indicator[0].Related_Project__c);
                         Track_Indicator__c[] tracked =  UtilitiesRecordTrack.getTrackIndicatorId(indicator[0].Id, act.Month_Number__c, act.Operation_Name__c);
                         UtilitiesRecordTrack.recordOrUpdate(tracked,  actual, act.End_At__c.date(), indicator[0].Id, act.Operation_Name__c);
                     }
                 }

             }
        } 
        
        
        if(indicatorFullName == 'Number of meetings with parents'
                                && projectName == 'School Of Hope')
        {
             Indicator_1__c[] indicator = UtilitiesRecordTrack.getIndicator(indicatorFullName, projectName);
             if(indicator.size() > 0)
             {
                 Decimal actual;
                 for(Activity_1__c act : newRecords)
                 {
                     if(act.Activity_Type__c == 'Meeting With Parent'
                        && act.Project_Name__c == UtilitiesRecordTrack.getProjectID(projectName))
                     {
                         actual = (Decimal) getTotalActivityOn(act.Month_Number__c, act.Operation_Name__c, act.Activity_Type__c, indicator[0].Related_Project__c);
                         Track_Indicator__c[] tracked =  UtilitiesRecordTrack.getTrackIndicatorId(indicator[0].Id, act.Month_Number__c, act.Operation_Name__c);
                         UtilitiesRecordTrack.recordOrUpdate(tracked,  actual, act.End_At__c.date(), indicator[0].Id, act.Operation_Name__c);
                     }
                 }

             }
        } 
        
      
        if(indicatorFullName == '# of hygiene club meeting carried out'
                                && projectName == 'WASH')
        {
             Indicator_1__c[] indicator = UtilitiesRecordTrack.getIndicator(indicatorFullName, projectName);
             if(indicator.size() > 0)
             {
                 Decimal actual;
                 for(Activity_1__c act : newRecords)
                 {
                     if(act.Activity_Type__c == 'hygiene club meeting carried out -(WASH)'
                        && act.Project_Name__c == UtilitiesRecordTrack.getProjectID(projectName))
                     {
                         actual = (Decimal) getTotalActivityOn(act.Month_Number__c, act.Operation_Name__c, act.Activity_Type__c, indicator[0].Related_Project__c);
                         Track_Indicator__c[] tracked =  UtilitiesRecordTrack.getTrackIndicatorId(indicator[0].Id, act.Month_Number__c, act.Operation_Name__c);
                         UtilitiesRecordTrack.recordOrUpdate(tracked,  actual, act.End_At__c.date(), indicator[0].Id, act.Operation_Name__c);
                     }
                 }

             }
        } 
        
        if(indicatorFullName == '# of sensitization campaigns carried out'
                                && projectName == 'WASH')
        {
             Indicator_1__c[] indicator = UtilitiesRecordTrack.getIndicator(indicatorFullName, projectName);
             if(indicator.size() > 0)
             {
                 Decimal actual;
                 for(Activity_1__c act : newRecords)
                 {
                     if(act.Activity_Type__c == 'sensitization campaigns'
                        && act.Project_Name__c == UtilitiesRecordTrack.getProjectID(projectName))
                     {
                         actual = (Decimal) getTotalActivityOn(act.Month_Number__c, act.Operation_Name__c, act.Activity_Type__c, indicator[0].Related_Project__c);
                         Track_Indicator__c[] tracked =  UtilitiesRecordTrack.getTrackIndicatorId(indicator[0].Id, act.Month_Number__c, act.Operation_Name__c);
                         UtilitiesRecordTrack.recordOrUpdate(tracked,  actual, act.End_At__c.date(), indicator[0].Id, act.Operation_Name__c);
                     }
                 }
                 
             }
        }
}

Trigger:
 
trigger RecordRelatedTrackIndicatorOnActivity on Activity_1__c (after insert, after update) {
    if(Trigger.isInsert)
    {
	  RecordTrackOnActivityHelper.recordTrack(Trigger.New, 'Number of meetings with parents', 'School Of Hope');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, 'Numbers of  training sessions held', 'School Of Hope');
        
        
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of training session conducted for volunteers', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of people sensitized on the importance of after-school activities', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of boys participating in after-school activities', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of girls participating in after-school activities', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of girls reading at the library', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of boys reading at the library', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of male adolescents attending training on sexual health and risk behavior linked to their age', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of female adolescents attending training on sexual health and risks behavior linked to their age', 'Comunity Development Campus'); 
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of youth participating in debate sessions', 'Comunity Development Campus');   
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of community leaders and members participating in Koze Lakay', 'Comunity Development Campus');   
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of community leaders and members participating in other community gatherings', 'Comunity Development Campus');   
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of community activities conducted by adolescents', 'Comunity Development Campus');   
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of community activities conducted by kids', 'Comunity Development Campus'); 
      
      
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, 'Number  extracurricular activities', 'School Of Hope');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of hygiene club meeting carried out', 'WASH');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of sensitization campaigns carried out', 'WASH');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of parent meetings held on WASH issues', 'WASH');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of Delmas 32 community members sensitized on WASH issues', 'WASH');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of concerts held by Little Kids Band', 'Music Heals International');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of concerts held by Little Kids Band with special guest musicians', 'Music Heals International');
  

     
    }
 	
    if(Trigger.isUpdate)
    {
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, 'Number of meetings with parents', 'School Of Hope');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, 'Numbers of  training sessions held', 'School Of Hope');
        
        
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of training session conducted for volunteers', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of people sensitized on the importance of after-school activities', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of boys participating in after-school activities', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of girls participating in after-school activities', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of girls reading at the library', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of boys reading at the library', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of male adolescents attending training on sexual health and risk behavior linked to their age', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of female adolescents attending training on sexual health and risks behavior linked to their age', 'Comunity Development Campus');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of youth participating in debate sessions', 'Comunity Development Campus'); 
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of community leaders and members participating in Koze Lakay', 'Comunity Development Campus');  
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of community leaders and members participating in other community gatherings', 'Comunity Development Campus');  
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of community activities conducted by adolescents', 'Comunity Development Campus');   
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of community activities conducted by kids', 'Comunity Development Campus'); 
        
        
      
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, 'Number  extracurricular activities', 'School Of Hope');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of hygiene club meeting carried out', 'WASH');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of sensitization campaigns carried out', 'WASH');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of parent meetings held on WASH issues', 'WASH');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of Delmas 32 community members sensitized on WASH issues', 'WASH');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of concerts held by Little Kids Band', 'Music Heals International');
      RecordTrackOnActivityHelper.recordTrack(Trigger.New, '# of concerts held by Little Kids Band with special guest musicians', 'Music Heals International');
    }
}

magine these functions being calling for every row in a CSV file or comming from mass update. even two rows, the governor limit exceipt raised.

If someone can help, I will realy appreciate that. I tried Map, but same reallity.
 
Hello! I am trying to write a unit test for my SMS to new lead trigger and controller. I have no idea on how to unit test for salesforce. please help!

My trigger is - 
trigger SMS_To_New on Lead (after insert) {
     
    Send_SMS_ControllerLead.Send(Trigger.newMap.keySet());
}


My class is - 
 
public class Send_SMS_ControllerLead {
    public String smsBody {get; set;}
    public boolean hasNumber {get; set;}
    public final String  fromNumber = '+1XXXXXXXXXX';// get it from twilio
      //after login click Phone Numbers tab in left sidebar
 
    public string dialCode = '+1'; // Add your dial Code of your country.
    public Send_SMS_ControllerLead(ApexPages.StandardController controller) {
       hasNumber = true;
    }
    public static void Send()
{
    String account = 'XXXXXXXXXXXXXXXXXXXXXXXXXX'; // Account SID on home tab
    String token  =   'XXXXXXXXXXXXXXXXXXXXXXXXXX'';//AUTH Token on home tab
    TwilioRestClient client = new TwilioRestClient(account, token);
 
    Id leadId = ApexPages.currentPage().getParameters().get('id');
 
    String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
    Lead a = [SELECT Phone FROM Lead WHERE Id = :leadId];
 
    if(a.Phone != null)
    {
        String phoneNumber = a.Phone;
        if(!phoneNumber.Contains('+1'))
        phoneNumber = '+1'+phoneNumber;// If by default dialCode is not
         //on Phone number we will ad it.
        System.debug('phoneNumber'+phoneNumber);
         Map<String,String> params = new Map<String,String> {
        'To'  => phoneNumber,
        'From' => '+1XXXXXXXXXX',
        'Body' => 'Thank you for applying with Fundwise! Next step is to get a credit report. Please check your email now for the next step.'
         };
         TwilioSMS sms = client.getAccount().getSMSMessages().create(params);
         SMS_Lead__c sentSMS = new SMS_Lead__c(From__c = '+1XXXXXXXXXX',To__c =phoneNumber, Body__c = 'Thank you for applying with Fundwise! Next step is to get a credit report. Please check your email now for the next step.');
         insert sentSMS;
 
    }
     
}
    // This method for Trigger
    @future(callout=true)
    public static void Send(Set<Id> setId)
    {
     
        List<Lead> newLead = [select id,Phone from Lead where id in :setId];
         
        String account = 'XXXXXXXXXXXXXXXXXXXXXXXXXX'; // Account SID on home tab
        String token  =   'XXXXXXXXXXXXXXXXXXXXXXXXXX'';//AUTH Token on home tab
        TwilioRestClient client = new TwilioRestClient(account, token);
 
        String baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        List<SMS_Lead__c> lstSMSLead = new List<SMS_Lead__c>();
         
        for(Lead leadObj : newLead)
        {
            if(leadObj.Phone != null)
            {
                String phoneNumber = leadObj.Phone;
                if(!phoneNumber.Contains('+1'))
                phoneNumber = '+1'+phoneNumber;// If by default dialCode is not
                 //on Phone number we will ad it.
                System.debug('phoneNumber'+phoneNumber);
                 Map<String,String> params = new Map<String,String> {
                'To'  => phoneNumber,
                'From' => '+1XXXXXXXXXX,
                'Body' => 'Thank you for applying with Fundwise! Next step is to get a credit report. Please check your email now for the next step.'
                 };
                 TwilioSMS sms = client.getAccount().getSMSMessages().create(params);
                  
                 SMS_Lead__c sentSMS = new SMS_Lead__c(From__c = '+1XXXXXXXXXXX',To__c= phoneNumber, Body__c = 'Thank you for applying with Fundwise! Next step is to get a credit report. Please check your email now for the next step.');
                 //insert sentSMS;
                lstSMSLead.add(sentSMS);
            }
        }
 
        if(lstSMSLead.size() > 0 )
        {
            insert lstSMSLead;
        }  
    }
}

 
Dear All:

I create a test class with Test Generator APP help, but I got some issues. Mainly, the code left me what I assume were junk characters, I tried to fix them but now I got Error: Compile Error: Method does not exist or incorrect signature: void ClientAccountSummary(List<CP_AccountSummary.ClientAccountSummary>) from the type CP_PieChartHelper at line 9 column 23.

Can you help me to figure out what's wrong? I'm very new in Test Classes. There is the code:
 
@isTest
 
private class CP_PieChartHelper_Test{
 
  static testMethod void test_ClientAccountSummary_UseCase1(){
 
    CP_PieChartHelper obj01 = new CP_PieChartHelper();
 
    CP_PieChartHelper.ClientAccountSummary (new List<CP_AccountSummary.ClientAccountSummary>());
 
  }
 
  static testMethod void test_AssetSummary_UseCase1(){
 
    CP_PieChartHelper obj01 = new CP_PieChartHelper();
 
    CP_PieChartHelper.AssetSummary (new List<CP_AccountSummary.AssetSummary>());
 
  }
 
  static testMethod void test_ApproachSummary_UseCase1(){
 
    CP_PieChartHelper obj01 = new CP_PieChartHelper();
 
    CP_PieChartHelper.ApproachSummary (new List<CP_AccountSummary.ApproachSummary>());
 
  }
 
  static testMethod void test_getAllPieChartsData_UseCase1(){
 
    CP_PieChartHelper obj01 = new CP_PieChartHelper();
 
    CP_PieChartHelper.getAllPieChartsData(new CP_ClientSummary(),new CP_AccountSummary());
 
  }
 
}

 
Hello. I am creating a custom controller to insert an event. I understand it has to be a custom controller so it can be fired from a global action on Salesforce1. I need Visualforce to fire an event when either the Contact (whoid) or Account (whatid) is selected on the page so that I can dynamically create the SOSL to restrict the Contact or Account to those that are related to each other. Users should not be able to select a Contact unrelated to an Account. How can I do this? Thanks so much.

VisualForce:
<apex:page controller="NewEvent">
<apex:form >
<apex:pageBlock title="Event Details">

<apex:pageMessages />
<apex:pageBlockSection title="Event Information">
    <apex:inputfield value="{!ev.subject}"/>
    <apex:inputfield value="{!ev.description}"/>   
    <apex:inputfield value="{!ev.startdatetime}"/>
    <apex:inputfield value="{!ev.enddatetime}"/>
    <apex:inputfield value="{!ev.whoid}"/>
    <apex:inputfield value="{!ev.whatid}"/>  
</apex:pageBlockSection>
        
<apex:pageBlockbuttons >
   <apex:commandbutton value="Save" action="{!save}"/>    
</apex:pageBlockbuttons>    
    
</apex:pageBlock>
</apex:form>
</apex:page>

Apex:
public class NewEvent {

public event ev { get; set; }
    
public newevent (){
    ev = new event();
    ev.CurrencyIsoCode = UserInfo.getDefaultCurrency();
    ev.OwnerId = UserInfo.getUserId();
    ev.StartDateTime = Datetime.now().addMinutes(-Datetime.now().minute());
    ev.EndDateTime = Datetime.now().addMinutes(60-Datetime.now().minute());   
}
    
public PageReference save() {
      return new ApexPages.StandardController(ev).save();
  }    
}
Hi Experts,

i have requriemnt where i need to update fields on event record, i wrote the code but it has some isslues like below.

1.e.location=sordermap.get(e.whatid).S__Site__c;: i am not able to populate the S__Site__c value  the event field called location its populating only id(S__Site__c is lookup field for another object called location__C)

2. e.Subject =sordermap.get(e.whatid).Subject__c;:
a) here i need to trim the subject value for first 20 characters 
b)subject filed already there is value coming from another logic so i need to append my subject value to it ( EG: A + test , here A is already value coming from another logic and test is the subject which i am adding through my logic but for me its showing as A +A+test , it means i am seeing A value two times i dont know why.
can anyone help me . Thanks in advance.


trigger sitesubjectupdateonevent on Event (before insert) 
{
  set<id> soidset = new set<id>();
    for(event e : trigger.new)
     {
       if(e.whatid!=null) 
        {
          soidset.add(e.whatid);
        }
     }

Map<id,S_Order__c> sordermap= new Map<id,S_Order__c>([select id, S__Site__c,Subject__c  from  S_Order__c where id in: soidset limit 50000 ]);
  
 for( event e: Trigger.new)
   {
    if(e.whatId!=null && sordermap.containskey(e.whatid))
    {
    
      e.location=sordermap.get(e.whatid).S__Site__c;
   
      e.Subject =sordermap.get(e.whatid).Subject__c;
    }
  }
    
}
I've just started into Apex coding and could use some help. I borrowed a Class that someone posted online that allows a user to ACCEPT or REJECT a lead.

Where it changes the Status to 'Working - Accepted' - I want that to be the trigger that CHANGES OWNER to whoever clicked the action. Can someone help me with the script?
public class AcceptLead {
    public Lead l;

    /**
    * The constructor
    *
    * @param controller The standard controller
    */
    public AcceptLead(ApexPages.StandardController controller) {
        this.l = (Lead) controller.getRecord();
    }

    /**
    * The page action that will accept the lead
    *
    * @return The page to goto after loading
    */
    public PageReference pageAction() {
        this.l.Status = 'Working - Accepted';

        update this.l;

        return new PageReference('/' + this.l.Id);
    }
}

 
Hello!

Attempting a script that allows the user to pick values freely with the exception of 3 values. If the users selects any of the 3 defined values, restrict the user from make any further revisions to the picklist. 

Below is my current attempt, this works to keep the user from selecting the 3 defined values per their user role, however I'm trying to allow them to select the value but then "lock" the value once it has been selected. Does this scenerio sound feasible via validation rule? 

AND((CONTAINS($UserRole.Name,'Contractor')), 
OR(ISPICKVAL(eo2__Project_Status__c, 'Work Complete') 
,ISPICKVAL(eo2__Project_Status__c, 'Batched') 
,ISPICKVAL(eo2__Project_Status__c, 'Incentive Authorized') 
))

Any help would be appreciated!

Thanks!

Michael
Hello Guru's,

I've created an Apex Class, a Visual Force Page, and a custom field named "Last Viewed By" earlier, the goal is to have the feature of knowing who last viewed an account record in SF. Both of the Apex Class and Visual Force page are working fine, although there's a bit issue, It messes up the "Last Modified By" Field as well. So for example: USER 1 viewed the Account named Account 1 (viewed only, no editting done), when User 2 views the same account both of the "Last Viewed By" and "Last Modified By" field are now showing USER 1 DD/MM/YYYY TIME. Any advise, or suggestions on what changes needs to be done on the codes below.

APEX CLASS
public class lastViewedAccount{
public Datetime cDT;
public String LongDate;
public String firstname;
public String lastname;
public String userid;
private final Account acct;
public lastViewedAccount(ApexPages.StandardController stdController) {
this.acct = (Account)stdController.getRecord(); }
public String getLongDate() {
cDT = System.now(); //Format the datetime value to your locale
LongDate = cDT.format('dd/MM/yyyy HH:mm'); return LongDate;
}
public void updateField() {
//Get the user info from the current user
firstname = System.Userinfo.getFirstName();
lastname = System.Userinfo.getLastName();
userid = System.Userinfo.getUserId();
//Get the Account record to be updated
Account a = [select Last_Viewed_By__c from Account where id = :acct.id limit 1];
//Assign values to Last Viewed By field &amp; update the record
a.Last_Viewed_By__c = (firstname + ' ' + lastname + ', ' + getLongDate());
update a;
}

}

Visual Force Page
<apex:page action="{!updateField}" extensions="lastViewedAccount" showheader="false" sidebar="false" standardcontroller="Account"> </apex:page>
Please help me add a line of code to my trigger.  I don't want the trigger to run if Date_Pushed_to_Production__c is populated.  This field resides on the custom object Project__c.  Thank you for looking at my question.  
Here is the trigger:


Trigger MoveToProduction on Opportunity (before insert, before update){

   List<ID> ProjIds = New List<ID>();

  for(Opportunity o : Trigger.new){
    if(o.Move_to_Production__c == true && o.RecordTypeId == '012a0000001FqTn'){
    
      ProjIds.add(o.Project__c);
  }

  List<Project__c> ProjList = [SELECT id, Move_to_ProductionP__c, Date_Pushed_to_Production__c FROM Project__c WHERE id in :ProjIds];
  for(integer i = 0 ; i < ProjList.size(); i++){
    If(ProjList[i].Date_Pushed_to_Production__c == null)
     
     ProjList[i].Move_to_ProductionP__c = true;
       ProjList[i]. Date_Pushed_to_Production__c = system.today();
      
  update ProjList;
  • August 16, 2017
  • Like
  • 0
What does Trigger.new list get when a trigger is fired?Does it get the records which caused the trigger to fire?
I am trying to write a trigger that will look at a field where a salesforce Id has been loaded.  I want to then have the trigger populate another field with the record's name.  The catch here is that the Id can be from any object including chatter objects.  Is this something that can be done since the object itself is not defined? Also, these records would need to handle in batches since they will be dataloaded.  I'm am only just learning apex so any help from the community would be really appreciated.

Thanks
Hi,

Iam trying to update field on oppournity, where recordid(lookup) is equal to 00528000001KyAT, need to update account id(lookup ) as 0012800000lIenH.
I have written a trigger

trigger updateif on Opportunity (before insert,before update) {
if(trigger.isBefore && (trigger.isInsert || trigger.isUpdate)){ 
          list<string> lstStr = new list<string>();
      for(opportunity opp : trigger.new){
          if(opp.record_id__c = '00528000001KyAT'){
              opp.update__c = '0012800000lIenH';
}
}
}
}

Help me to  fix this
It is  a Apex code 
My pick list value  for TimeFrame __c  is  12:00 - 08:00 AM.  
I  need to insert into string  starttime__c  as 12 Am and  endTime__C as  8 AM from that value that i m getting ffor TimeFrame __c
  • August 14, 2017
  • Like
  • 0
We are using professional org.
Having a process builder which updates a field on some condition with formula type.

this is how the formula is ,i am using & between them.

I am having datetime field which is used in the update field but the format is being changed 


"Start Date:" & TEXT(DATETIMEVALUE([Opportunity].Date_Time_Start__c )) &
"End Date:" &TEXT([Opportunity].Date_Time_End__c ) &

This is the format i am lookinh for 
2/27/2018 4:00 PM

but this is how i am getting

2017-02-27 21:00:00Z 

How can i get this fixed?? 

 
On https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_expressions_operators_understanding.htm
it is stated that:

"Unlike Java, == in Apex compares object value equality, not reference equality, except for user-defined types."
"For sObjects and sObject arrays, == performs a deep check of all sObject field values before returning its result. Likewise for collections and built-in Apex objects." 

Why are the two asserts below failing then? If you look at the debug logs with the "Debug Only" option selected you should see that all 3 objects re identical.

Are the asserts below failing for you as well or is it just a glitch in my dev org?

// Two different ways to get a DescribeSObjectResult object 
        DescribeSObjectResult dsor1 = Account.SObjectType.getDescribe();
        DescribeSObjectResult dsor2 = Schema.sObjectType.Account;
        
        // Another way to get the DescribeSObjectResult using the Schema object
        List<DescribeSObjectResult> l =  Schema.describeSObjects(new List<String> {'Account'});
        DescribeSObjectResult dsor3 = l[0];
        
        System.assert(dsor1 == dsor2); // succeeds
       //System.assert(dsor1 == dsor3); // fails
      // System.assert(dsor2 == dsor3); // fails
       System.assert(dsor1.getsObjectType() == dsor3.getsObjectType()); // succeeds
       System.assert(dsor2.getsObjectType() == dsor3.getsObjectType()); // succeeds
        
        // If you look at the debug logs with the "Debug Only" option selected
        // you should see that the objects below are identical
        system.debug('dsor1: ' + dsor1);
        system.debug('dsor2: ' + dsor2);
        system.debug('dsor3: ' + dsor3);

 
  • March 13, 2018
  • Like
  • 0
I'm currently using an Apex Class to generate a list of records owned by a specific User.
 
public TelemarketerDialing(){

        if(ApexPages.currentpage().getParameters().get('leadgenerator') == null)
                       {myParam = UserInfo.getUserId();}

        else{myParam = ApexPages.currentpage().getParameters().get('leadgenerator');}
        }

      public String myParam { get; set; }

I build a Visualforce page for Managers to basically click in to the list of any User using the Visualforce page URL of that individual LeadGenerator's page.
 
<td><a href="https://corere--c.na50.visual.force.com/apex/DoorKnockerPortal?leadgenerator=0056A000000f0af">Angel</a></td>

        <td><a href="https://corere--c.na50.visual.force.com/apex/TelemarketerPortal?leadgenerator=0056A000000e779">Antonio</a></td>

        <td><a href="https://corere--c.na50.visual.force.com/apex/TelemarketerPortal?leadgenerator=0056A000001IVgU">Ary</a></td>
I'm wondering if there's a way to user the UserID to display the name of the User you are viewing on the page.

Something like:
public String LeadGeneratorName = getUserInfo(myParam).UserName;
Is this possible?


 
I have the following very simple VF page to display two dependent picklists (3 tiers total) using a custom controller. When I attempt to save the VF page, I get the error message above.
In the developer console, I see two Problems at Line 0. 1) ABS_Services_Input, Unknown property 'String.Services__c and 2) "Duplicate value found: duplicates value on record with id:" (Yes, literally. No id # given.)

<apex:page controller="ABSServicesController">
    <apex:messages style="color:red"></apex:messages>  
    <apex:form >
        <apex:pageBlock title="Dependent Picklist Entry">
            <apex:repeat value="{!serviceList}" var="svcItem">
                <apex:pageBlockSection title="{!svcItem.Services__c}" columns="1">
                    <apex:pageBlockSection title="{!svcItem.Capabilities__c}" columns="1">
                        <apex:pageBlockSection title="{!svcItem.Sub_Capabilities__c}" columns="1">
                        </apex:pageBlockSection>
                    </apex:pageBlockSection>
                </apex:pageBlockSection>
            </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page> 

This is my Custom Controller code:

public with sharing class ABCServicesController{

    public String serviceList { get; set; }
 
    public List<ServiceOffered__c> servicesList{get;set;}
    public Map<String, Map<String, List<String>>> serviceMap{get;set;}
    
    public ABCservicesController(){
        serviceMap = new Map<String, Map<String, List<String>>>();
        
        servicesList = [Select ID, Services__c, Capabilities__c, Sub_Capabilities__c From ServiceOffered__c];
        
        for(ServiceOffered__c svcItem : servicesList) {
            if(serviceMap.containsKey(svcItem.Services__c)) {
                if(serviceMap.get(svcItem.Services__c).containsKey(svcItem.Capabilities__c)) {
                    serviceMap.get(svcItem.Services__c).get(svcItem.Capabilities__c).add(svcItem.Sub_Capabilities__c);
                } else {                    
                    serviceMap.get(svcItem.Services__c).put(svcItem.Capabilities__c, new List<String>{svcItem.Sub_Capabilities__c});
                }
            } else {
                Map<String, List<String>> m = new Map<String, List<String>>();
                m.put(svcItem.Capabilities__c, new List<String>{svcItem.Sub_Capabilities__c});
                serviceMap.put(svcItem.Services__c, m);
                //new Map<String, List<String>>{svcItem.Capabilities__c : new List<String>{svcItem.Capabilities__c}}
            }
        }
    }     
}

I do not know if it is relevant but earlier I was getting an unknow property error serviceList related to the line "Public List<ServiceOffered__c> serviceList{get;set;}".  
My path toward resolution, besides asking all of you great folks, is to figure out why the variable svcItem was expected to be something other than a string when every service being pulled into the List is a string.
Thanks in advance,
Wade
I am trying to cover a method which uses formula field.
This is my test class code:

SObject1__C coltype = new SObject1__C();
coltype.name = 'Name-3312';
insert coltype;
System.debug('--->SObject1.Name = '+coltype.name); // Gives 'Name-3312';

SObject2__C colObj = new SObject2__C();
colObj.SObject1__C = coltype.Id;
insert colObj;  

SObject3__C newCollP = new SObject3__C();
newCollP.SObject2__C = colObj.Id,
insert newCollP;

SObject3__C has a fomula field named 'Col_Type__C' which is evaluated as follows:
"SObject2__r.SObject1__r.Name"
System.debug('--->newCollP.Col_Type__C = '+ newCollP.Col_Type__C); //returns a2Hg0000001tqQ2

This 'Col_Type__C' field's value is then used in a method in a helper class which i am trying to cover. As posted by many, I have tried to query the object SObject3__C and populate the field Col_Type__C in the test class as below. But it's not populatting the formula field's value as 'Name-3312'. 
newCollP = [SELECT Id,SObject2__r.SObject1__r.Name, Col_Type__C from SObject3__C where Id=:newCollP.id];

When I debug Col_Type__C value in helper class it returns some ID. I need the value of  as name of SObject1__C.

What is missing in my code? How can I get the formula field populated? 

Any help is appreciated!
Hi all,

my problem is i have one last update date field.
i want to update this field on case record whenever i click on new task,log a call and new events on case record and also whnever i change status field and priority field it should be updated.

Thanks
Hi,
i am getting a post call out from external stsyem. i am creating or updating a  custom object record out of it. Can anyone please let em know how to write a test classs for it?
Here is my code:

global without sharing class ContactService {
    
    @HttpPost
    global static String insertContact(ContactInfoParser contactRec){
        //creation or update of application record. Mapping the fields from ContactInfoParser class.
        String RecordTypeApplicationId = Schema.SObjectType.Application__c.getRecordTypeInfosByName().get('Test').getRecordTypeId();        
        Application__c applicationObj = new Application__c();
        applicationObj.Id = contactRec.application.applicationId;
        applicationObj.applicant__c = contactRec.contact.contactId;
        applicationObj.RecordTypeId = RecordTypeApplicationId;
        applicationObj.assessPriorLearning__c = contactRec.application.assessPriorLearning;
        applicationObj.Status__c = contactRec.application.status;
        applicationObj.reason__c= contactRec.application.reason;
        applicationObj.priorLearningNotes__c= contactRec.application.priorLearningNotes;
        applicationObj.applingForCredit__c= contactRec.application.applingForCredit;
        upsert applicationObj;


Thanks
  • March 09, 2018
  • Like
  • 0
I am trying to insert portal user records and receiving this error


System.DmlException: Insert failed. First exception on row 0; first error: PORTAL_USER_ALREADY_EXISTS_FOR_CONTACT, portal user already exists for contact: []

Here is the code
 
@IsTest static void testRegFormWithNewUserAddress11() {
    
             
        Contact con = new Contact();
          con.Firstname = 'test';
          con.LastName ='test';
         con.OtherPhone = '8765432167';
         con.Organization_Type__c = 'test';
          con.Email ='Sitetestg466@hotmail.com';
        insert con; 
             Order__c ordr = new Order__c();
          ordr.Contact__c = con.Id;
          ordr.Account__c = a.Id;
          insert ordr;
          
       Order_Line__c ordrline = new Order_Line__c();
          ordrline.Order__c = ordr.id;
          insert ordrline;
             
    ControllerTest controller = new ControllerTest();        
controller.con = con;
        controller.acc = a;

       	controller.Password= 'testpass123';
        controller.checkIfContactExists();
        controller.checkIfAccountExists();
          
         controller.setTab();
 
          
             Profile p = [select Name, id From Profile where UserLicense.Name like '%Customer Community%' limit 1];
      
    		
           User u = new User ();
          u.FirstName = 'test';
          u.LastName ='test';
          u.Email ='testemail'+Math.round(Math.random()*Math.pow(10, 7))+'@testemail.com';
          u.Username = 'testemail'+Math.round(Math.random()*Math.pow(10, 8))+'@testemai.com';
          u.Alias ='test';
          u.CommunityNickname ='tst';
          u.ContactId =con.Id;
          u.LanguageLocaleKey = 'en_US';
                    u.LocaleSidKey ='en_CA';
                    u.TimeZoneSidKey ='America/Chicago';
         			u.ProfileId = p.Id;
                    u.EmailEncodingKey = 'UTF-8';
                 insert u; 
         
   
     }

The Controller code is below
 
List<User> existalready = [select id,Contact.FirstName,Username,Contact.LastName from user where username =:Email and IsActive = true LIMIT 1];
                if(existalready.size()<0){
                    for(User u: existalready){
insert u ;
insert con;

Can someone help in this scenario​
  • March 09, 2018
  • Like
  • 0
@isTest
public class MaintenanceRequestTest {
    
	
    @isTest static void testSetup(){
        
        
                List<Product2> equip = new List<Product2>();
        		equip.add(new Product2(Name ='Test Equipament', 
                                         Maintenance_Cycle__c = 10,
                                         Cost__c = 100,
                                         Current_Inventory__c = 10,
                                         Lifespan_Months__c = 10,
                                         Replacement_Part__c = true,
                                         Warehouse_SKU__c = 'abc'));
            
                        
                        insert equip;
        
        System.debug( 'Equip' + equip);
        
        Database.insert(equip, false);
        
        
        
    }
    
    @isTest static void testMaintenanceRequest(){
        
        MaintenanceRequestTest.testSetup();
        
        List<Case> listInsert = new List<Case>();
        
        List<Case> listUpdate = new List<Case>();
        
      	Id equipId = [SELECT Id FROM Product2 LIMIT 1].Id;
         System.debug('Product2' + equipId);
        
        
           for(Integer i = 0 ; i < 300; i++){
            Case caseInsert = new Case(Type='Routine Maintenance', Status = 'New', Origin = 'Phone');
			caseInsert.Equipment__c = equipId;            
        
            listInsert.add(caseInsert);
        }
        Database.insert(listInsert, false);
        
        
        Test.startTest();
        
        System.assertEquals(300, listInsert.size());
        
        
        for(Case c: listInsert){
            c.Status = 'Closed';
            listUpdate.add(c);
        }
        
        Database.update (listUpdate, false);
        
        System.assertEquals(300, listUpdate.size());
       
       
        
        User usuario = [SELECT id FROM User WHERE Id =: UserInfo.getUserId()];
              
    	System.runAs(usuario){
               
        	
             List<Case> ClosedCaseList = [SELECT Type, Status, Equipment__c, Date_Due__c, Date_Reported__c, Vehicle__c FROM Case WHERE status = 'Closed'];    
			
          	 MaintenanceRequestHelper.updateWorkOrders(ClosedCaseList);  
            
            }
        
       Test.stopTest(); 
    }
    
   
   
     	
}

 
i have a vf  page
<apex:page sidebar="false" showHeader="false" controller="definition_overview_controller" tabstyle="Label__c" id="page">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="/soap/ajax/15.0/connection.js" type="text/javascript"></script>
<script src="/soap/ajax/15.0/apex.js" type="text/javascript"></script>
<script>
function setFocusOnLoad() {}
$(document).ready(function(){
 $(".fieldInput").focusin(function() {
 var tempObj = $(this).closest('td').prev('td').find('input').val();
 if(tempObj.length >0){       
  sleep(100).then(()=>{
   sforce.connection.sessionId='{!GETSESSIONID()}';
   var tempList = sforce.apex.execute("ListofLabel","getAllLabels",{Objname:tempObj});
   $(".fieldInput").autocomplete({source: tempList});              
    });   
   }
});  
});

function sleep (time) {
    return new Promise((resolve) => setTimeout(resolve, time));
}       
</script>
<apex:sectionHeader title="Mapping Object" subtitle="Form" id="header"/>
<apex:form id="form">
<apex:pageBlock id="pageblock" >
 <apex:pageBlockTable title="Related List" value="{!label}" var="l" id="pageblocktable"> 
  <apex:column headerValue="Lebal Name" id="col1" >
      <apex:outputText value="{!l.name}">
     
       <apex:param value="{!l.name}" AssignTo="{!levelName}"/>
   </apex:outputText>
  </apex:column>
  
  <apex:column headerValue="SFobject" id="col2">
   <apex:inputText value="{!l.FormId__r.Parent_object_Name__c}">
   
       <apex:param value="{!l.formId__r.Parent_object_Name__c}" AssignTo="{!objectName}" />
   </apex:inputText>
  </apex:column>
  
  <apex:column headerValue="SFField" id="col3">
   <apex:inputText value="{!field}" styleClass="fieldInput"/>
  </apex:column>
  <apex:column >
          <apex:commandButton value="Save" action="{!save}"/>
  </apex:column>
  
 </apex:pageBlockTable>

    </apex:pageBlock>
</apex:form>
</apex:page>

controller:


public class definition_overview_controller{ 
 Mapping__c mapp=new Mapping__c();
 //list<Mapping__c> li{get;set;}
 
 public id i;
 public String field{get;set;}
 //public  string x{get;set;}
 public String levelname{get;set;}
 public string objectname{get;set;}
 
 public definition_overview_controller()
 {
  i=ApexPages.CurrentPage().getParameters().get('id');
  
 // li=new list<Mapping__c>();
  //li.add(mapp);
 }
 public list<label__C> label;
 public list<Label__c> getlabel()
 {
  label=[select Name,FormId__c,description__c,Label__c,FormId__r.Parent_object_Name__c from Label__c where FormId__c=:i];
  return label;
 }
 public void Save(){
 
   
            mapp.LabelD__c=levelname;
           // System.debug(mapp);
            mapp.SFObject__c=objectname;
            mapp.SFfield__c=field;
            insert mapp;
          //  li.add(mapp);
    /*      System.debug(li);
     for(integer i=0;i<li.size();i++)
     {
         insert li;
     }*/
         
  
 }
}

Note : i am not able to store multiple record at a time it show Error-->

Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LabelID]: [LabelID]
Error is in expression '{!save}' in component <apex:commandButton> in page visualforcepage_webners_assignment_page2: Class.definition_overview_controller.Save: line 31, column 1
 
How do I solve this? 


Apex script unhandled trigger exception by user/organization: 005C0000008pPXs/00D80000000L8DR
 
RHX_Opportunity: execution of AfterInsert
 
caused by: System.SObjectException: Field Opps_Received_20163__c is not editable
 
Class.rh2.PS_Rollup_Context.setParentsToUpdate: line 571, column 1
Class.rh2.PS_Rollup_Context.run: line 510, column 1
Class.rh2.PS_Rollup_Helper.performSync: line 545, column 1
Class.rh2.ParentUtil.performTriggerRollups: line 128, column 1
Trigger.RHX_Opportunity: line 7, column 1
 
list<contact> clst = new list<contact>();
for(contact con : [Select id, otherphone from contact]) {
    con.otherphone = '768906543333';
    clst.add(con);
}
update clst;

Getting SOQL 101 Error Can Any one Correct Me. I am run this code in developer console
  • March 08, 2018
  • Like
  • 0
Hi,

This is challenge from Apex Academy: Fundamental Salesforce Coding Techniques by David Liu.
I want one child case but this trigger is creating Child case depending on the keywords like if I enter 2 keywords in Parent description, it will create 2 child cases.

Here is the trigger code
trigger CheckSecretInformation on Case (after insert, before update) {

	String childCaseSubject = 'Warning: Parent case may contain secret info';

	//Step 1: Create a collection containing each of our secret keywords
	Set<String> secretKeywords = new Set<String>();
	secretKeywords.add('Credit Card');
	secretKeywords.add('Social Security');
	secretKeywords.add('SSN');
	secretKeywords.add('Passport');
	secretKeywords.add('Bodyweight');

	//Step 2: Check to see if our case contains any of the secret keywords
	List<Case> casesWithSecretInfo = new List<Case>();
	List<String> SecretKeywordFound = new List<String>();
	for(Case myCase : Trigger.new) {
		if(myCase.Subject != childCaseSubject) {	
			for(String keyword : secretKeywords) {
				if(myCase.Description != null && myCase.Description.containsIgnoreCase(keyword)) {
					casesWithSecretInfo.add(myCase);
					SecretKeywordFound.add(keyword);
					System.debug('Case ' + myCase.Id + ' include secret keyword ' + keyword);
				}
			}
		}	
	}

	// Step 3: If our case contains a secret keyword, create a child case
	List<Case> casesToCreate = new List<Case>();
	
	for(Case caseWithSecretInfo : casesWithSecretInfo) {
		Case childCase        = new Case();
		childCase.subject     = childCaseSubject;
		childCase.ParentId    = caseWithSecretInfo.Id;
		childCase.IsEscalated = true;
		childCase.Priority    = 'High';
		childCase.Description = 'At least one of the following keywords were found ' + SecretKeywordFound;
		casesToCreate.add(childCase);
	
	}
	insert casesToCreate;

}

If I use break; in for loop, It will create one child case but it shows only first keyword not all the keyword that should be displays in one Child case.
 
trigger CheckSecretInformation on Case (after insert, before update) {

	String childCaseSubject = 'Warning: Parent case may contain secret info';

	//Step 1: Create a collection containing each of our secret keywords
	Set<String> secretKeywords = new Set<String>();
	secretKeywords.add('Credit Card');
	secretKeywords.add('Social Security');
	secretKeywords.add('SSN');
	secretKeywords.add('Passport');
	secretKeywords.add('Bodyweight');

	//Step 2: Check to see if our case contains any of the secret keywords
	List<Case> casesWithSecretInfo = new List<Case>();
	List<String> SecretKeywordFound = new List<String>();
	for(Case myCase : Trigger.new) {
		if(myCase.Subject != childCaseSubject) {	
			for(String keyword : secretKeywords) {
				if(myCase.Description != null && myCase.Description.containsIgnoreCase(keyword)) {
					casesWithSecretInfo.add(myCase);
					SecretKeywordFound.add(keyword);
					System.debug('Case ' + myCase.Id + ' include secret keyword ' + keyword);
					break;
				}
			}
		}	
	}

	// Step 3: If our case contains a secret keyword, create a child case
	List<Case> casesToCreate = new List<Case>();
	
	for(Case caseWithSecretInfo : casesWithSecretInfo) {
		Case childCase        = new Case();
		childCase.subject     = childCaseSubject;
		childCase.ParentId    = caseWithSecretInfo.Id;
		childCase.IsEscalated = true;
		childCase.Priority    = 'High';
		childCase.Description = 'At least one of the following keywords were found ' + SecretKeywordFound;
		casesToCreate.add(childCase);
	
	}
	insert casesToCreate;

}

Note: Please Don't use Map collection or SOQL. If there is a possibility that anyone can achieve this without MAP! 

Thanks