Illegal assignment from List to Id

apex

Hello Iam new to salesforce and Iam trying to assign a queue to a owner field that is in the custom object through a trigger along with some other critera – everything is working except for the Assigned To where it is dumping the following error:

Error: Illegal assignment from List to Id

   for(City_Census__c c: Trigger.New) {
        if(c.Auto_Approve__c == true){
            c.Approval_Status__c = 'Approved';
        }
        
        if(c.City__c == 'Makati') {             
            c.OwnerId = [SELECT Id FROM Group WHERE Type = 'Queue' and Name='Makati Owner'];
        }
    }
  

Best Answer

As mentioned, you are attempting to assign c.OwnerId to a potential list.
Also you make a query to Database in a for loop, this is wrong !!
According to Apex Best Practice , see it here trailhead

Avoid SOQL queries and DML statements inside loops.

I would rewrite your code in this way :

List<Group> groups = [SELECT Id FROM Group WHERE Type = 'Queue' and Name='Makati Owner' limit 1];
for(City_Census__c c: Trigger.New) {
    if(c.Auto_Approve__c == true){
        c.Approval_Status__c = 'Approved';
    }
    
    if(c.City__c == 'Makati') {             
        c.OwnerId = groups.isEmpty() ? null : groups[0].Id;
    }
}
Related Topic