Activity Forums Salesforce® Discussions How to compare Trigger.new values with Trigger.old values

  • How to compare Trigger.new values with Trigger.old values

    Posted by Deepak on August 22, 2019 at 10:17 am

    I have a junction object 'Related Products' which has master detail relationship with 'Contact' and have a lookup relationship with 'Product'. And I have added a related list of 'Related Products' in Contact detail page where user can create new Related Product from the Contact and can add multiple Products to it.

    Now my requirment is "if any user selects a product which is already selected to that contact should through error".
    For example, I have contact called "Test Contact111", In it I have created one Related Product "RP-0001" and selected a Product called "Prod111", It will get to save and will show in the Contact's detail page under 'Related Products' section.
    Again from the same Contact I will create another Related Product "RP-0002" and again will select the Same Product "Prod111", now the trigger need to throw an error states "Prod111 is already selected"

    Prachi replied 4 years, 8 months ago 2 Members · 1 Reply
  • 1 Reply
  • Prachi

    Member
    August 22, 2019 at 10:55 am

    Hi Deepak,

    Try this-

    trigger RelatedProduct  on RelatedProduct__c (before insert)
    {
    Set<Id> setProductId = new Set<Id>();
    Set<Id> setOfProductHaveRelation = new Set<Id>();
    for (RelatedProduct__c objRelatedProduct : Trigger.New)
    {
    setProductId.add(objRelatedProduct.Product__c);
    }
    for (RelatedProduct__c objRelatedProduct :[SELECT Id, Product__c FROM RelatedProduct__c WHERE Product__c IN: setProductId])
    {
    setOfProductHaveRelation.add(objRelatedProduct.Product__c);
    }
    for (RelatedProduct__c objRelatedProduct : Trigger.New)
    {
    if(!setOfProductHaveRelation.contains(objRelatedProduct.Product__c )) continue;
    objRelatedProduct.addError('This Product already have the Relation.');
    }

    Thanks.
     

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos