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
AntonyasLenAntonyasLen 

SOQL limit doesn't work

Hi,

 

i have a custom field called "url" on Product2 i just want to set it to my OpportunitLineItem when i'll add one to my opportunity.

i wrote the trigger below:

 

trigger SetSpecialProductInfo on OpportunityLineItem (before insert) {
    for(OpportunityLineItem op : Trigger.new){
    	if(op.Id_uad__c == 0){
    		String url = [Select URL__c From Product2 Where Id = :op.PricebookEntry.Product2Id limit 1];
			op.Image_Url__c = url;
			update op;
    	}
    }
}

i got this error: Save error: Illegal assignment from LIST<Product2> to String

i was thinking that if i use the "limit 1" i'll prevent the multiple result but it looks like doesn't work =/

 

Thanks

Best Answer chosen by Admin (Salesforce Developers) 
neophyteneophyte

SOQL always returns SObjects record(s). You should change the code to:

 

Product2 p = [Select URL__c From Product2 Where Id = :op.PricebookEntry.Product2Id limit 1];
op.Image_Url__c = p.URL__c;

All Answers

neophyteneophyte

SOQL always returns SObjects record(s). You should change the code to:

 

Product2 p = [Select URL__c From Product2 Where Id = :op.PricebookEntry.Product2Id limit 1];
op.Image_Url__c = p.URL__c;

This was selected as the best answer
AntonyasLenAntonyasLen

thanks it's helpfull, so everytimes we have to use used the object type isn't it?

neophyteneophyte

Generally, you use a list (List<ObjectType>), unless it's certain that the query will return only one record.