0

I just start in APEX and I have been trying to develop a trigger which isnt working, The requirement is that

I have a Sales Target Name field that should auto-populate in a form when I associate a Salesman (which is a lookup field on a User) once Salesman is fullfill in the form and we click save the trigger should autopopulate the Sales Target Name with the User Alias associate to the Salesman fill in the form

the trigger is

trigger populateSTName on Sales_Target__c (before insert , before update){ 
    Set<Id> setConIds = new Set<Id>();
    for (Sales_Target__c obj : trigger.new) {
        if (obj.Name != null) {
            setConIds.add(obj.Name);
        }
    }
    Map<Id, User> mapCon = new Map<Id, User>([Select Id, Alias from User where id in: setConIds]);
    for (Sales_Target__c obj : trigger.new) {
        if (obj.Name != null) {
            if (mapCon.containsKey(obj.Name)) {
                User c = mapCon.get(obj.Name);
                obj.Name = c.Alias;
            }
        }
    }
}

THE FORM enter image description here

Is there someone who can help me? Thanks in advance

1
  • 1
    Welcome to SFSE! Could you please edit your post to describe the behavior you are currently seeing, or any error messages you receive or view in your debug logs?
    – David Reed
    Commented Mar 28, 2022 at 22:35

1 Answer 1

0

I think you may be out of luck on this one.

Semantic errors aside (I think that if (obj.Name != null) should be if (obj.Salesman__c != null), with similar replacements for all other instances of obj.Name except for obj.Name = c.Alias;), you're running into a system validation rule.

The standard Name field is always required (for the objects that have a Name field).

When you push the "Save" button, Salesforce goes through a specific order of execution.

System validation is the second execution step, whereas your before trigger (any before triggers) are the fourth. So Salesforce is stopping you before you even get into your before trigger.

There may be a chance that you could get away with this if you were using a Visualforce page or a Lighting Web Component (LWC for short), but if you're using the standard UI record creation page then I don't believe you can escape system validation.

1
  • Wow thanks a lot it works ! Thank you so much to have take the time to answer me
    – user113068
    Commented Mar 29, 2022 at 13:39

You must log in to answer this question.

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