function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AntjeAntje 

SOQL/apex Trigger

Hello,
I could use some help on my trigger. I am trying to copy some fields from two standard objetcs into one custom object (dataTable__c). I am trying to copy several fields from Opportunities as well as some fields from Tasks (if the task is related to opportunity) into my custom object. Tasks has a lookup realtionship to opportunities (related to = what). My custom object has a master detail relationship to opportunity (opporunityName1__c). 
I am new to apex and would really appreciate your help. I figured out one part of the equation but I am not sure how I would include a trigger that works on the second object. I don't want to have two seperate triggers working seperately .The end result should be that all the fields from both objects are in th same record. I am pretty sure I will need to use SOQL but I can't seem to find exactly what I need. Here is what I got so far. THANK YOU

Trigger AutoDT on Task (after insert,after update) {
List <DataTable__c> newdt = new List <DataTable__c> ();
for (Task t : Trigger.new) {
DataTable__c dts = new DataTable__c ();
dts.TaskSubject__c = t.subject;
dts.TaskStatus__c = t.status;
dts.TaskPriority__c = t.priority;
dts.TaskComments__c = t.Description;

dts.taskDateTaskAssigned__c = t.date_task_assigned__c;
dts.TaskDueDate__c = t.ActivityDate;

newdt.add (dts);
}
insert newdt;
}
Best Answer chosen by Antje
Pankaj_GanwaniPankaj_Ganwani
Hi Antje,

Trigger.new always shows the list of new version of sobject records(which are inserted, undeleted or just before update). Now, you have created a trigger on after insert and after update, so you can do following iteration on trigger.new(list of inserted Task object records).

Set<Id> setOppId = new Set<Id>();//declare a set in trigger to store the opp ids related to Task
List<Task> lstFilteredTask = new List<Task>();//storing only those task which belongs to Opportunity record.
for(Task objTask : Trigger.new)
{
      if(objTask.whatId!=null && objTask.WhatId.getSobjectType() == Opportunity.SobjectType())
      {
           setOppId.add(objTask.whatId);
           lstFilteredTask.add(objTask);
      }
}


// Fetch all Opportunity records where Id in set:
Map<Id,Opportunity> mapIdToOpp = new Map<Id,Opportunity>[select Id, Name, ....FROM Opportunity WHERE ID IN : setOppId];

//Now, Iterate over the lstFilteredTask and do the following:

List<DataTable__c> lstDataTable = new List<DataTable__c>();// list to hold the data table records which has to be inserted in sf.
for(Task objTask : lstFilteredTask)
{
      if(mapIdToOpp.containskey(objTask.WhatId))
   {
      Opportunity objOpp = mapIdToOpp.get(objTask.WhatId);// hold the opp object record corresponding to what id
      DataTable__c dts = new DataTable__c ();
     dts.TaskSubject__c = t.subject;
     dts.TaskStatus__c = t.status;
     dts.TaskPriority__c = t.priority;
     dts.TaskComments__c = t.Description;

     dts.taskDateTaskAssigned__c = t.date_task_assigned__c;
     dts.TaskDueDate__c = t.ActivityDate;
     
    //do the mapping of custom object fields with Opportunity fields and add it to the list. Let's say you have A__c, B__c and C__c fields on DataTable__c that needs to be mapped with Opportunity fields Name, CloseDate and StageName respectively. Then, you can use following:
    
    dts.A__c = objOpp.Name;
    dts.B__c = objOpp.CloseDate;
    dts.C__c = objOpp.StageName;
    
    lstDataTable.add(dts);
   }

}

insert lstDataTable;

Please try with above mentioned code and let me know if you experience any issues with it. I have put the possible commenting near the code statements to indicate the purpose.

All Answers

sandeep sankhlasandeep sankhla
Hi Antje,

Opportunity which field you want to map with Datatable field..In your case if task is having opportunity as parent then somefields should be match from opportunity...

Thanks,
Sandeep
Pankaj_GanwaniPankaj_Ganwani
Hi,

1. Firstly, you iterate over Trigger.new, check whether whatid belongs to Opportunity, if so add the Task record to a list and get all the whatIds into a set.

2. Fetch all Opportunity records where Id in set:
Map<Id,Opportunity> mapIdToOpp = new Map<Id,Opportunity>[select Id, Name, ....FROM Opportunity WHERE ID IN : setOpp];

3. Now, Iterate over the list collected in step 1 and do the following:

for(Task objTask : lstTask)
{
      if(mapIdToOpp.containskey(objTask.WhatId))
   {
      Opportunity objOpp = mapIdToOpp.get(objTask.WhatId);
      DataTable__c dts = new DataTable__c ();
     dts.TaskSubject__c = t.subject;
     dts.TaskStatus__c = t.status;
     dts.TaskPriority__c = t.priority;
     dts.TaskComments__c = t.Description;

     dts.taskDateTaskAssigned__c = t.date_task_assigned__c;
     dts.TaskDueDate__c = t.ActivityDate;
     
    //do the mapping of custom object fields with Opportunity fields and add it to the list.
   }

}

//Atlast insert the list.
AntjeAntje
I am trying to get the following fields from Task: Assigned to (owner), subject, status, priority, date_task_assigned__c, activityDate, Description. From Opportunity, I would like to copy the following fields into my custom object:Opportunity Name (Name), contact__c, stageName, Probability, closeDate, createdDate Thank YOU!!!
sandeep sankhlasandeep sankhla
Antje,

Pankaj solved your problem..you can follow the steps which he mentioned to achieve your goal..

Thanks,
Sandeep
Pankaj_GanwaniPankaj_Ganwani
Hi,

You can fetch all the Opportunity fields in SOQL as mentioned in step 2 and in step 3 you can map them with custom object fields.


2. Fetch all Opportunity records where Id in set:
Map<Id,Opportunity> mapIdToOpp = new Map<Id,Opportunity>[select Id, Name, contact__c, stageName, Probability, closeDate, createdDate
FROM Opportunity WHERE ID IN : setOpp];

3. Do the mapping in forloop
 
AntjeAntje
You guys make it sound so easy! :)
I appeciate your help...
AntjeAntje
Do you know of where I could find an example of what Pankaj described?
 
Pankaj_GanwaniPankaj_Ganwani
Hi,

The examples are rare to find on google since there can be multiple scenarios similar to it. Please let me know if you are having any problem with it.
AntjeAntje
Hello Pankaj, I know it has been a while. I am continuing to struggle with this trigger, in particular with step one. You advised me that I am iterating over Trigger.new. I am not sure what that means. Whatid belong to the Task object and not the Opportunity object. I know this probably seems very easy to you but this is a foreign language for me. Again, your help is most certainly appreciated. Best regards Firstly, you iterate over Trigger.new, check whether whatid belongs to Opportunity, if so add the Task record to a list and get all the whatIds into a set.
Pankaj_GanwaniPankaj_Ganwani
Hi Antje,

Trigger.new always shows the list of new version of sobject records(which are inserted, undeleted or just before update). Now, you have created a trigger on after insert and after update, so you can do following iteration on trigger.new(list of inserted Task object records).

Set<Id> setOppId = new Set<Id>();//declare a set in trigger to store the opp ids related to Task
List<Task> lstFilteredTask = new List<Task>();//storing only those task which belongs to Opportunity record.
for(Task objTask : Trigger.new)
{
      if(objTask.whatId!=null && objTask.WhatId.getSobjectType() == Opportunity.SobjectType())
      {
           setOppId.add(objTask.whatId);
           lstFilteredTask.add(objTask);
      }
}


// Fetch all Opportunity records where Id in set:
Map<Id,Opportunity> mapIdToOpp = new Map<Id,Opportunity>[select Id, Name, ....FROM Opportunity WHERE ID IN : setOppId];

//Now, Iterate over the lstFilteredTask and do the following:

List<DataTable__c> lstDataTable = new List<DataTable__c>();// list to hold the data table records which has to be inserted in sf.
for(Task objTask : lstFilteredTask)
{
      if(mapIdToOpp.containskey(objTask.WhatId))
   {
      Opportunity objOpp = mapIdToOpp.get(objTask.WhatId);// hold the opp object record corresponding to what id
      DataTable__c dts = new DataTable__c ();
     dts.TaskSubject__c = t.subject;
     dts.TaskStatus__c = t.status;
     dts.TaskPriority__c = t.priority;
     dts.TaskComments__c = t.Description;

     dts.taskDateTaskAssigned__c = t.date_task_assigned__c;
     dts.TaskDueDate__c = t.ActivityDate;
     
    //do the mapping of custom object fields with Opportunity fields and add it to the list. Let's say you have A__c, B__c and C__c fields on DataTable__c that needs to be mapped with Opportunity fields Name, CloseDate and StageName respectively. Then, you can use following:
    
    dts.A__c = objOpp.Name;
    dts.B__c = objOpp.CloseDate;
    dts.C__c = objOpp.StageName;
    
    lstDataTable.add(dts);
   }

}

insert lstDataTable;

Please try with above mentioned code and let me know if you experience any issues with it. I have put the possible commenting near the code statements to indicate the purpose.
This was selected as the best answer
S ShahS Shah
public class insertContact
{
    public static void insertMethod(List<Opportunity> newOpp, Boolean isInsert, Boolean isBefore)
    {
        if(isInsert== true && isBefore==true)
        {
            for(Opportunity op1: newOpp)
            {
                if(op1.closedate == system.today())
                {
                    op1.addError('Close dat can not be todays date');
                }
                
                /*if(op1.name == 'Hiral')
                {
                    Contact con = new Contact();
                    con.LastName = op1.name;
                    insert con;
                }*/
            }
        }
    }
}