You need to sign in to do that
Don't have an account?
Opp Line items to Asset Apex Trigger
I am modifying the Salesforce Labs Appexchange app Opportunity Products to Assets to include a new field. Here is my code:
trigger CreateAssetonClosedWon on Opportunity (after insert, after update) { for(Opportunity o: trigger.new){ if(o.isWon == true && o.HasOpportunityLineItem == true){ String opptyId = o.Id; OpportunityLineItem[] OLI = [Select UnitPrice, Quantity, PricebookEntry.Product2Id, PricebookEntry.Product2.Name, Description, Converted_to_Asset__c From OpportunityLineItem where OpportunityId = :opptyId and Converted_to_Asset__c = false]; Asset[] ast = new Asset[]{}; Asset a = new Asset(); for(OpportunityLineItem ol: OLI){ a = new Asset(); a.AccountId = o.AccountId; a.Product2Id = ol.PricebookEntry.Product2Id; a.Quantity = ol.Quantity; a.Price = ol.UnitPrice; a.PurchaseDate = o.CloseDate; a.Status = 'Purchased'; a.Description = ol.Description; a.Name = ol.PricebookEntry.Product2.Name; a.SerialNumber = o.Dongle_ID__c; a.Contact = o.Contact_Person__c; ast.add(a); ol.Converted_to_Asset__c = true; } update OLI; insert ast; } }}
I have added this line:
a.Contact = o.Contact_Person__c;
a.Contact is a standard field on the Asset object which is a lookup(Contact) and o.Contact_Person__c is a custom lookup related to contact.
Problem I am having on saving this with the new line of code is I receive this error message:
Error: Compile Error: Illegal assignment from Id to SOBJECT:Contact at line 21 column 13
Can someone guide me on what I need to do please?
Instead of
a.Contact = o.Contact_Person__c;
Use
a.Contact = o.Contact_Person__r;
By the way, if you copy your code from the trigger EDIT page (rather than the trigger view) it'll preserve the formatting when you paste in the code. This makes it easier to read :D
Ok I tried:
a.Contact = o.Contact_Person__r;
I also entered this line of code:
a.Related_Opportunity__c = o.Name;
a.Related_Opportunity__c is a Custom lookup field on the Asset object to the Opportunity.
When I edit the Opportunity Stage to Closed/Won and try and save I get an error message that says:
Review all error messages below to correct your data.
Apex trigger CreateAssetonClosedWon caused an unexpected exception, contact your administrator: CreateAssetonClosedWon: execution of AfterUpdate caused by: System.StringException: Invalid id: Altered Images - GMC: Trigger.CreateAssetonClosedWon: line 21, column 13
Line 21, column 13 is this new line of code.
What am I doing wrong?
How about this...
a.ContactId = o.contact_person__c; a.Related_Opportunity__c = o.id;