0

I am currently in the process of trying to get a trigger that will create a new contract each time an asset is created (within a certain product family) When our salesforce was setup our consultant decided against using normal assets and setup a new object for assets hence the custom asset object.

I have managed to create the trigger to create the contract but the problem i am encountering is getting the trigger to link the newly created asset and contract together.

Below is a the code im using any help would be appreciated!

Thanks

trigger create_contract_from_custom_asset on Asset_Custom__c (before insert) {

for(Asset_Custom__c a: trigger.new){

    If(a.Product_Family__c <> 'Consumables' && a.Product_Family__c <> 'Hardware'){

        string newasId = a.id;        
    Contract[] Con = new Contract[]{};
    Contract c = new Contract();

    c.AccountId = a.Account__c;
    c.StartDate = a.Purchase_Date__c;  
    c.Asset__c = a.name;  

    con.add(c);

    Insert con; 

    }

} }

  • Is asset__c a lookup to asset object? If so, you should populate with newasId or just a.id, like c.asset__c = a.id; – dzh Apr 26 '16 at 9:26
  • Asset__c is a lookup from contracts to assets Lookup(Asset Custom) – Benjy Hunt Apr 26 '16 at 9:45
1

1) If you want to link a newly created record with a different one then you'd have to use the former record's id, hence you need an after insert trigger. 2) Never use DML statements inside a loop

trigger create_contract_from_custom_asset on Asset_Custom__c (after insert) {
  Contract[] Con = new Contract[]{};
for(Asset_Custom__c a: trigger.new){

    If(a.Product_Family__c <> 'Consumables' && a.Product_Family__c <> 'Hardware'){

      Contract c = new Contract();
      c.AccountId = a.Account__c;
      c.StartDate = a.Purchase_Date__c;  
      c.Asset__c = a.name;  
      // I added a new field linktoasset__c which is of type lookup relationship
      c.LinkToAsset__c = a.id

    con.add(c);

    }
} 

  insert con;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.