+ Start a Discussion
mxalix258mxalix258 

Mutliple conditions for trigger

If I create a trigger that inserts new records based on a given condition, for example:

 

for (object__c obj : Trigger.new) {

  if (obj.name ='x')

 Do this


 add obj. to list

 

How could I do multiple SOQL conditions and upload all the records to the same list to be imported? For example:

 

for (object__c obj : Trigger.new) {

  if (obj.name ='x')

     obj.field='Some Value"

 

  if(obj.name ='y')

     obj.field='Some other value"


 add obj. to list

 

Thanks!

sfdcfoxsfdcfox

You've basically got it right, but the devil is in the details. Being that your question is generic, its hard to give a straightforward answer. If the same record might overlap on conditions, you might need to determine a winner. If there shouldn't be duplicates, that might need a map. There are a variety of issues that might arise. Of course, feel free to ask and we'll help you along, but it seems like you have a decent grasp on the situation; it sounds like you just need a bit more studying on the various types of memory structures available.

mxalix258mxalix258

The same record shouldn't overlap in conditions....we are trying to create a new record off the application object. So when the staff=true and job title =x we want to create a new record and set certain values. Additionally, when job title =x and record type =y we want to create a new record, but assign different values.

 

Does that make sense? I just get a little confused on how to loop through two different sets of SOQL statements and assign different values to those records, and then add them to the same list for insert.

 

Thanks!

sfdcfoxsfdcfox
Sounds straightforward. Try something like this:

MyOtherRecord__c[] newRecords = new MyOtherRecord__c[0];
map<id,recordtype> recordTypes = new map<id,recordtype>([select id,developername from recordtype where sobjecttype='application__c']);
for(application__c record:trigger.new) {
if( record.jobtitle__c == 'x' ) {
if(recordtypes.get(record.recordtypeid).developername=='x') {
newRecords.add(new Myotherobject__c( ... values for job title='x', recordtype='x');
}
if(recordtypes.get(record.recordtypeid).developername=='y') {
newrecords.add(new myotherobject( ... values for job title='x', recordtype='y');
}
}
}
insert newRecords;

Basically, so long as the records being created are of the same type, you can add them together into the same list, and insert them at once.