[SalesForce] How to insert and get value for lookup field (Trigger)

I'm a new developer.

I try to create new record by trigger.When create orderitem(line item) in order I need system to automate create new record in custom table name "Service" and copy Order id , Orderitem id , Product from orderitem to custom object name Service.

from code as below I can command system to create new record but I have a ploblem with Lookup field becuase error unexpected token

trigger Update_OrderRecord on OrderItem (After Insert) {
    list<Service_available_del__c> AddPA = new list<Service_available_del__c>();
    for( OrderItem o : Trigger.new ) {
        Service_available_del__c PA = new Service_available_del__c
        (
            Order_Item_Number__c = o.OrderItemNumber,
            Order_product__c= [select Product2 OrderItem where OrderItemNumber='0000000028'],
            Quantity__c = o.Quantity,
            UnitPrice__c = o.UnitPrice
        );

        AddPA.add(PA);         
    }

    insert AddPA;
}

Best Answer

Lets start with populating lookup fields:

Order_product__c= [select Product2 OrderItem where OrderItemNumber='0000000028']

It's clear what you're trying to do, but that won't work. Firstly, the SOQL statement can return an (empty) list or object, but a lookup field is actually populated with the ID. Conveniently you have this value as you're in the After Insert context!

Order_product__c = o.id; 

That's it!

Though, I'd like to point your attention to bulkification. It's good to see that you're putting all your new records in a list and only inserting your list of new records to the database once your for-loop is over. That's a core way of dealing with bulk processing of records, another important one is avoiding SOQL queries in your for-loops.

So in any future trigger, where you would need to query for related data, you'd first collect all the ID's for which you need to query, do the query to get the data, and then apply it to your list of records.

Welcome to developing in salesforce and salesforce.Stackexchange :-)

Related Topic