Apex Trigger-Salesforce before insert

894 Views Asked by At

I have two custom objects 1. Customer 2.Complaint and they are lookup relationship with each other.

I have problem like that the below trigger is not working. My requirement is like that before inserting complaint, first it will check email id and contact number and then complaint will register.

trigger Demo on Complaint__c (before insert) {
    Set<Id> customerIds = new Set<Id>();
    for (Shan__Complaint__c complaint : Trigger.new) {
        customerIds.add(complaint.Shan__customer__c);
    }
    Map<String, Shan__cust__c> customers =
        new Map<String, Shan__cust__c>([SELECT Shan__cust_contact__c, Shan__cust_email__c
                                        FROM Shan__cust__c WHERE id IN: customerIds]);
    for (Shan__Complaint__c complaint : Trigger.new) {
        Shan__cust__c customer = customers.get(complaint.Shan__customer__c);
        if (customer == null || complaint.Shan__E_mail__c == customer.Shan__cust_email__c
            && complaint.Shan__Phone_Number__c == customer.Shan__cust_contact__c) {
            complaint.adderror('Your phone and Email does not exists in out database ');
        }
    }
}
1

There are 1 best solutions below

1
On

This trigger should not be compiled at all.

You should see error

Loop variable must be of type Complaint__c

Trigger.new is a List<Complaint__c>

So, there are 2 errors:

for (Shan__Complaint__c complaint : Trigger.new) {
    customerIds.add(complaint.Shan__customer__c);
...

for (Shan__Complaint__c complaint : Trigger.new) {
    Shan__cust__c customer = customers.get(complaint.Shan__customer__c);
...