+ Start a Discussion
SFDC coderSFDC coder 
hi all,
i need to get the ids of all the contacts associated to an event.
i.e the contacts that we add into the name field.
However,when i query the whoId field,i just get the primary contact id and not all the other assciated contact ids.

can anyone please help?
Best Answer chosen by SFDC coder
EnreecoEnreeco
Try to query the EventRelation SObject (http://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_eventattendee.htm), with "IsWhat = false" and "IsParent = true".
This should work.

--
May the Force.com be with you!
Lakshmi SLakshmi S 
Hi All,

Q). What is a future method ? When we are going to use Future methods? Example program for Future method and Schedulable class for Future method?

Give me reply anyone.....
Best Answer chosen by Lakshmi S
NagendraNagendra (Salesforce Developers) 
Hi Lakshmi Narasimha,

What is Future Method:

A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you'd like to run in its own thread, on its own time.

When to use Future Method:

If you want to make the execution of the apex program to run asynchronously then we make use of future method.When you specify
future , the method executes when Salesforce has available resources. For example, you can use the future annotation when making an asynchronous Web service callout to an external service.

Apex class with Future Method:
public class AccountProcessor 
{
  @future
  public static void countContacts(Set<id> setId) 
  {
      List<Account> lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
      {
          List<Contact> lstCont = acc.contacts ;
          
          acc.Number_of_Contacts__c = lstCont.size();
      }
      update lstAccount;
  }
}

Test class for the above:
@IsTest
public class AccountProcessorTest {
    public static testmethod void TestAccountProcessorTest() 
    {
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;

        Contact cont = New Contact();
        cont.FirstName ='Bob';
        cont.LastName ='Masters';
        cont.AccountId = a.Id;
        Insert cont;
        
        set<Id> setAccId = new Set<ID>();
        setAccId.add(a.id);
 
        Test.startTest();
            AccountProcessor.countContacts(setAccId);
        Test.stopTest();
        
        Account ACC = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
        System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);
  }
  
}

Instead of a Schedulable class, try using a batch class. batch classes can be scheduled using the UI, and can call @future methods.
global class ScheduledDispatcher Implements Schedulable{

    public Interface IScheduleDispached{
        void execute(SchedulableContext sc);
    }

    global void execute(SchedulableContext sc){
        Type targetType = Type.forName('{HANDLERNAME');
        if(targetType != null){
            IScheduleDispached obj = (IScheduleDispached)targetType.newInstance();
            obj.execute(sc);
        }
    }


}

public class {HANDLERNAME} implements ScheduledDispatcher.IScheduleDispached {

  public void execute(SchedulableContext sc)
    {

        //Call your Future Method Here

    } 

}
For more information refer to the below link.
http://amitsalesforce.blogspot.sg/2015/02/future-methods-in-salesforce.html

Kindly mark my solution as the best answer if it helps you.

Best Regards,
Nagendra.P
vajralavajrala 

i not understanding usage of junction object .

Please explain usage and how to create junction object with a example

Best Answer chosen by Admin (Salesforce Developers) 
Anup JadhavAnup Jadhav

Hi Vajrala,

 

Salesforce supports 2 kinds of relationships like Master Detail and Lookup. They are both one-to-many relationship, and they are both  defined from the many-to-one side, that is from a child to a parent. They can be made one-to-one relationship by adding validation rules, or maybe triggers to enforce the one-to-one nature, i.e. only one child is allowed.

 

Junction objects are used to create many to many relationships between objects. If you take the Recruiting application example, you can see that a Position can be linked to many Candidates, and a Candidate can apply for different Positions. To create this data model you need a third object "Job Application" that links the 2.

 

So you'd create a lookup field for both Position and Candidate object on the "Job Application" object. This will establish many to many relationship between Position and Candidate via the "Job Application" object known as the junction object.

 

Fore more information, read this article http://wiki.developerforce.com/page/A_Deeper_look_at_SOQL_and_Relationship_Queries_on_Force.com.

 

Anup

 

 

 

atharva Vispute 3atharva Vispute 3 
Hi,

 Create an apex trigger on Resource to make sure that It does not exceeds Project assignment limit as per Defined on Project types. 
·         If Project.Type == Hot than max 4 Resources Allowed to be created under that project 
·         If Project.Type == Warm than max 2 Resources Allowed to be created under that project 
·         If Project.Type == Cold than max 1 Resource is Allowed to be created under that project 
  
Example: Consider there is project named “TUV” with Type as “Warm” than system should only allow max 2 resources to be relate to TUV Project, if User tries to related more than 2 resources than System should Throw error that “Project Assignment Limit Reached” .
Plzz help me to find this solution in trigger. 

Thanks!!
Best Answer chosen by atharva Vispute 3
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Atharva,

Can you try the below apex trigger.
 
trigger Resourcescount on Resource__c (before insert,before update) {
    set<id> projectids= new set<id>();
    resource__c oldrs= new resource__c();
    for(Resource__c rs:Trigger.new){
        if(Trigger.isupdate)
             oldrs= trigger.oldmap.get(rs.id);
        
        if((Trigger.isinsert && rs.Project_Name__c!=null) || (Trigger.isupdate && rs.Project_Name__c!=oldrs.Project_Name__c) ){
            projectids.add(rs.Project_Name__c);

        }
    }

    map<id, Project__c>mapproj=new map<id,Project__c>([select id,Name,Type__c,(select id from resources__r) from project__C where id in :projectids]);
    
    for(Resource__c rse:Trigger.new){
        if(mapproj.containsKey(rse.Project_Name__c)){

           Project__c pre= mapproj.get(rse.Project_Name__c);
            system.debug('pre.Type__c'+pre.Type__c);
            system.debug('pre.resources__r.size()'+pre.resources__r.size());
            if(pre.Type__c=='Hot' && pre.resources__r.size() >3){
               
                rse.adderror('you canot create more than 4 child records for project');
            }
            if(pre.Type__c=='Warm' && pre.resources__r.size() >1){
               
                rse.adderror('you canot create more than 2 child records for project');
            }
            if(pre.Type__c=='cold' && pre.resources__r.size() ==0){
               
                rse.adderror('you canot create more than 1 child records for project');
            }
        }
    }
    
}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,
jkcjkc 
Hi,
I'm in a terrible dilemma with the trigger. I was wondering why there is no id assigned on the record anymore
trigger trigger_Account on Account(before insert, before update){
  for( Account acc : Trigger.new){
    system.debug('Account id: ' + acc.id);
  }
}
this change affected some of my previous triggers
Best Answer chosen by jkc
ManojSankaranManojSankaran
Hi,

Your trigger will fire in two condition before insert and before update.

In before insert - id value wont be there....since the record is not inserted into database.
in before update - id value will be there and you will be albe to use that id for calcualtion.

Only in After Insert you will get the id of that record.


Let me know if you need more clarification. If it answers your question please mark it as answer.

Thanks
Manoj S
Sumesh ChandranSumesh Chandran 
The below batch class will be processing a little over 2.5 million records. The START method will be sending in the whole 2.5 million records to the execute method and the execute method does the processing on each of the 2.5 million records inside a for loop. 
Also the for loop has a SOQL inside which I believe cannot be avoided to get the right numbers. 
Is this the right way of doing this or are there any other better ways. Please help!

Also when the running the below batch class I get the First Error: Too many query rows error.
 
global class MDUSquadRawDataBatchTest implements Database.Batchable<sObject>, Database.Stateful {  
    List<Address_Master__c> addressList = new List<Address_Master__c>();
    Set<String> addresses = new Set<String>();
   
    // Start Method
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator('SELECT Street_Address__c,City_Name__c FROM MDU_Squad_Raw_Data__c');
    }   
    
    // Execute method
    global void execute(Database.BatchableContext BC, List<MDU_Squad_Raw_Data__c> rawData) {        
        for(MDU_Squad_Raw_Data__c mduRawData: rawData) {
            List<MDU_Squad_Raw_Data__c> addressData = [SELECT Street_Address__c,City_Name__c,Province_Code__c,Postal_Code__c,Internet_Service__c,Video_Service__c,Phone_Service__c FROM MDU_Squad_Raw_Data__c WHERE Street_Address__c=:mduRawData.Street_Address__c AND City_Name__c=:mduRawData.City_Name__c];
            String fullAddress = addressData[0].Street_Address__c+' '+addressData[0].City_Name__c+' '+addressData[0].Province_Code__c+' '+addressData[0].Postal_Code__c;
            
            Address_Master__c theAddress = new Address_Master__c();
            if(!addresses.contains(fullAddress.substringBeforeLast(' '))) {
                theAddress.Name = addressData[0].Street_Address__c;
                theAddress.City_Name__c = addressData[0].City_Name__c;
                theAddress.Province_Code__c = addressData[0].Province_Code__c;
                theAddress.Postal_Code__c = addressData[0].Postal_Code__c; 
                fullAddress = addressData[0].Street_Address__c+' '+addressData[0].City_Name__c+' '+addressData[0].Province_Code__c+' '+addressData[0].Postal_Code__c;
                theAddress.Full_Address_Ext_Id__c = fullAddress;

                addresses.add(fullAddress.substringBeforeLast(' '));
                addressList.add(theAddress); 
            }                                                     
        }            
        Database.Upsert(addressList, Address_Master__c.Fields.Full_Address_Ext_Id__c, true);
    }
    // Finish Method    
    global void finish(Database.BatchableContext BC) {
        
    } 
}

I request if someone could please help me with this, as I am dealing with this for some time, with no idea on how to fix this.
Best Answer chosen by Sumesh Chandran
Andrew GAndrew G
if you are still struggling, here is a code example that may point you in the right direction:
//Loop1 - get street and city name data into two lists
list<string> streetList = new List<string>();
list<string> cityList = new List<string>();
for(MDU_Squad_Raw_Data__c mduRawData: rawData) {
  streetlist.add(mduRawData.StreetAddress__c);
  cityList.add(mduRawData.CityName__c);
}
//do query:
List<MDU_Squad_Raw_Data__c> addressData = [SELECT Street_Address__c, City_Name__c, Province_Code__c, Postal_Code__c, Internet_Service__c, Video_Service__c, Phone_Service__c 
    FROM MDU_Squad_Raw_Data__c 
    WHERE Street_Address__c IN :streetList 
        AND City_Name__c IN :cityList];

//Loop addressData to make Map with Key street~city
Map<string,MDU_Squad_Raw_Data__c> mapAddressData = new Map......
for(MDU_Squad_Raw_Data__c raw : addressData){
  //psuedo - if no key, then add
  if !(mapAddressData.containsKey(raw.Street_Address__c+'~'+raw.City_Name__c){
      mapAddressData.add(raw.Street_Address__c+'~'+raw.City_Name__c, raw);
  }
}

//now we loop the original list checking the map for the key and then update as required
list<MDU_Squad_Raw_Data__c > updateList = new....
for(MDU_Squad_Raw_Data__c raw: rawData) {
    if(mapAddressData.containsKey(raw.Street_Address__c+'~'+raw.City_Name__c)){
        MDU_Squad_Raw_Data__c address = mapAddressData.get(raw.Street_Address__c+'~'+raw.City_Name__c);
        //now update the raw record with address record
        raw.postalcode = addres.province code;
//etc
        updateList.add(raw);
     } //endi f
}//end loop
if (updateList.size()>0){
   update udpateList;
}

Regards
Andrew
Saurav Roy 15Saurav Roy 15 
Hello Everyone,
Can anyone please explain the significance of the Test.startTest() and Test.stopTest() in terms of asynchronous calls/apex ? I am aware of the governer limits being reset. 
Best Answer chosen by Saurav Roy 15
AbhishekAbhishek (Salesforce Developers) 
Hi Saurav,

As you have already know by now that Apex is governed by certain boundaries. The term coined for this is 'Governor Limits'.

There are two additional system static methods provided by Apex. These methods, Test.startTest and Test.stopTest, are used when testing governor limits. Or in other words, executing test scenarios with a larger data set.

These static methods allow a test method to separate the Apex resources and governor limits being used to prepare and initialize the dataset from the resources and limits used during the actual test execution.

Bottom Line - 

Governor limits are reset when the Test.startTest appears and the code between Test.startTest and Test.stopTest executes in a fresh set of governor limits (Context changes). Also, Test.stopTest appears, the context is again moved back to the original code.

Example -

you have 100 lines of code in your test class.

you have start test at 30 
you have stop test at 70

So the line of code from 30 -70 is the indifferent context of governor limits and
line 1-30/71-100 in different contexts. 

Total of 2 contexts here.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Regards,
Salesforce Support.
Rahul Jain 262Rahul Jain 262 
List<Account> lstAccrecords = new list<Account>();
for (integer counter = 1; counter <= 200; counter++)
{
    Account Acc = new Account();
    
        Acc.name = 'Testing for bulkification';
        Acc.AnnualRevenue = '2000'+counter;
        Acc.BillingAddress = 'Delhi';
        Acc.Phone= '898231851'+counter;
    
}
if(!lstAccrecords.isempty())
{
    insert lstAccrecords;
}
Best Answer chosen by Rahul Jain 262
Ruwantha BulegodaRuwantha Bulegoda
You are trying to assign invalid variable types for Annual Revenue and Billing Address. Annual Revenue is an integer value but with your '2000' (with quotes) it is assigned as strings. Remove the quotes. Then the address is a composite field. This means it is created with multiple fields as mentioned below. So you have to populate the city, street, and other values separately. Here is the working code for you. Also please mark this as the correct answer after checking.
List<Account> lstAccrecords = new list<Account>();
for (integer counter = 1; counter <= 200; counter++)
{
    Account Acc = new Account();

    Acc.name = 'Testing for bulkification';
    Acc.AnnualRevenue = 2000+counter;
    Acc.BillingCountry = 'India';
    Acc.BillingCity = 'Bombe';
    Acc.BillingPostalCode = '111';
    Acc.BillingStreet = '';
    Acc.billingCity = '';
    Acc.Phone= '898231851'+counter;

}
if(!lstAccrecords.isempty())
{
    insert lstAccrecords;
}

 
fiona gentryfiona gentry 
Hi Gurus,
How do i  Import Apex Classes Dev Sandbox into Visual Studio Code After successfully doing  SFDX: Authorise Org for my dev org which is a scratch org sandbox, basically I would like to execute my apex unit tests from Visual studio code..but the problem is I see only LWC project got created with project.json file  ..Here is my VSCode

User-added image

Regards,
Fiona
Best Answer chosen by fiona gentry
sachinarorasfsachinarorasf
Hi <fiona>,

After successfully doing  SFDX: Authorise Org, Please follow the following steps :
Step 1: Go to the Manifest folder in your created project.
Step 2: Right-click on the package.xml file.
Step 3: Select the' Retrieve source in Manifest from org' option from the drop-down list.
After successfully retrieved the source file, you can find the Apex classes in the 'force-app' folder.

I hope you find the above solution helpful. If it does, please mark it as Best Answer to help others too.

Thanks and Regards,
Sachin Arora
www.sachinsf.com
Michael MMichael M 
Hello, I have a snippet of JSON that looks like this:
"dates": [
{
"name": "Service",
"qualifier": "472",
"date": "2020-09-29"
},
{
"name": "Plan Begin",
"qualifier": "346",
"date": "2020-09-01"
},
{
"name": "Issue",
"qualifier": "102",
"date": "2020-06-01"
}
],

I need to be able to get the values from each "object" individually. 
I am getting the list like this:

Map<String, Object> wholeResponse = (Map<String, Object>) JSON.deserializeUntyped(response2.getBody());
Map<String, Object> result = (Map<String, Object>) wholeResponse.get('result');
List<Object> lstdates = (List<Object>) result.get('dates');

But after that I am getting stuck. How would I be able to get the name, qualifier, and date from each object contained in this list? (This may be a basic question, but I am a newbie to json parsing:))
 
Best Answer chosen by Michael M
Maharajan CMaharajan C
Hi Micheal,

We have to use the for loop on lstdates then only we can access the  name, qualifier, and date from each object.

Here below for loop will run for three times.So, In each looping you can access the object details with help of Map<String, Object> inside for loop.

When the loop run first time you will see the name as Service in debug. In 2nd time the name is Plan Begin and in 3rd time name will be printed as Issue. So similarly we can see the other 2 values from object with the help of  dateattr.get('qualifier') && dateattr.get('date')

for (Object dt : lstdates) {
Map<String, Object> dateattr = (Map<String, Object>)dt;
     System.debug( ' name --> ' + dateattr.get('name') );    
     System.debug( ' qualifier --> ' + dateattr.get('qualifier') );
     System.debug( ' date --> ' + dateattr.get('date') );
 }

use the below link to understand the JSON untyped deserialization.
https://opfocus.com/json-deserialization-techniques-in-salesforce/#:~:text=The%20best%20way%20to%20discover,through%20the%20use%20of%20System.

Thanks,
Maharajan.C