1

I have two objects one is standard object (Contact) and custom (Payment__c) and they have lookup from Payment__c to Contact. My requirement when ever Payment__c record is created corresponding PaymentConfirmed__c checkbox on Contact should be ticked.

I have tried trigger but functionality not working. Can any one help me with this?

TRIGGER:

trigger checkboTrigger on Payment__c(after Insert) 
{

    List ids = new List(); List conn3 = new List();

    for(Payment__c pay: Trigger.new)
    { 
        ids.add(pay.id); 
    }

    List conn2 = [SELECT id ,PaymentConfimed__c from contact where id in: ids];

    for(contact conn :conn2) 
    {
        conn.PaymentConfimed__c = true;
        conn3.add(conn);
    } 

    update conn3;
}
2
  • What's your error? Jul 10, 2017 at 20:31
  • Please always used the type safe collection like List<Id> ids = new List<Id>();
    – user46657
    Jul 11, 2017 at 11:22

2 Answers 2

4

You're building a list of Payment__c Id values, not Contact Id values. Also, there's no need to have a separate list, you can just do this:

trigger checkboTrigger on Payment__c(after Insert) {
    Set<Id> contactIds = new Set<Id>();
    for(Payment__c record: Trigger.new) {
        contactIds.add(record.Contact__c);
    }
    Contact[] records = [SELECT Id FROM Contact WHERE Id = :contactIds FOR UPDATE];
    for(Contact record: records) {
        record.Payment_Confirmed__c = true;
    }
    update records;
}

You could also just use the Process Builder for this, and avoid the hassle of using code.

0


According to your question Payment is having a lookup on Contact. So when you are creating the record for the Contact there you can see the lookup field of Payment but when you are creating the record for Payment we won’t be able to get which Contact checkbox needs to be checked.

But If payment object having the lookup of contact on it then this trigger will work.

Apex Trigger

trigger ContactCheckBox on Payment__c (before insert){
Set<id> conid = new Set<id>(); // Try to use set to avoid duplicate record
    for(Payment__c pay: Trigger.new){
        if(pay.contact__c != null){
            conid.add(pay.contact__c); //Selecting only those contacts who are in payment
        }   
    }

    if(conid.size() > 0 ){
        List<contact> Conlist = [SELECT id ,Payment_Confirm__c from contact  where id in :conid ];

        for(contact conn :Conlist){
            conn.Payment_Confirm__c = true;
        }

        update Conlist; 
    }   
}

I hope it will help you!!

Regards,
Ajay

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .