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
BobsterBobster 

Nested maps? Lists? For loops? HELP!

Hi guys,

 

I have been absolutely pulling my hair out over how to get the information I need out of the db into my trigger without putting SOQL queries within FOR loops (I'm trying to be a good boy). I'm pretty new with programming altogether so I've been having trouble getting my head around the concepts as much as the syntax; hope you can help.

 

I have custom object called BMCServiceDesk__Incident__c which has an Owner ID in it. Using this, I need to get the profile name of that user. I want to do this kind of thing, but properly using the necessary collections:

 

for (BMCServiceDesk__Incident__c inc : trigger.new){

List<User> users = [SELECT ProfileId FROM User WHERE Id = :inc.OwnerId LIMIT 1];
List<Profile> profiles = [SELECT Name FROM Profile WHERE Id = :users[0].ProfileId LIMIT 1]; inc.Team_Name__c = profiles[0].Name; }

 Here's what I have so far for the rest of the trigger:

 

public void OnBeforeInsert(BMCServiceDesk__Incident__c[] newObjects){

	Account itStaffAccount = [SELECT Id FROM Account WHERE Name = 'CMC IT Staff' LIMIT 1];
	Profile sdClientProfile = [SELECT Id FROM Profile WHERE Name = 'ServiceDesk Client' LIMIT 1];
		
	Set<Id> clientIds = new Set<Id>();
		
	for(BMCServiceDesk__Incident__c inc : newObjects){
		clientIds.add(inc.BMCServiceDesk__FKClient__c);
	}
		
	Map<Id, User> clients = new Map<Id, User>([SELECT ProfileId FROM User WHERE Id IN :clientIds]);		
	
	for(BMCServiceDesk__Incident__c inc : newObjects){
			
		if (clients.get(inc.BMCServiceDesk__FKClient__c).ProfileId != sdClientProfile.Id){
			inc.BMCServiceDesk__FKAccount__c = itStaffAccount.Id;
		}

		inc.Team_Name__c = null;
		Boolean isQueue = OwnerIdIsQueue(inc.OwnerId);
			
		if (isQueue == true){
			inc.Team_Name__c = 'Unassigned';
		}
		else {
			inc.Team_Name__c = <PROFILE NAME OF INCIDENT OWNER>;
		}
			
		system.debug('Team Name = ' + inc.Team_Name__c);
		}
	}
	
private Boolean OwnerIdIsQueue (Id ownerId){
	
	List<QueueSobject> queueIds = [SELECT QueueId FROM QueueSobject WHERE SobjectType = 'BMCServiceDesk__Incident__c'];

	for (QueueSobject q : queueIds){
		if (ownerId == q.QueueId) {
			return true;
		}
	}
	return false;
}

 If anyone could give me some pointers I'd be really grateful!

Dev@Force.ax647Dev@Force.ax647

Here you go

 

Set<Id> ownerIDs=new Set<Id>();
for (BMCServiceDesk__Incident__c inc : trigger.new){
    ownerIDs.add(inc.OwnerId);
}
Map<Id,User> users = new Map<Id,User>([SELECT Id,Profile.Name FROM User WHERE Id IN :ownerIDs ]);
for (BMCServiceDesk__Incident__c inc : trigger.new){
    inc.Team_Name__c = users.get(inc.OwnerId).Profile.Name;
}