0

I have below apex trigger on Account that will create records on custom object Alert_vod__c, whenever there is an update on specific fields (as declared in fieldset) of Account.

Trigger:

trigger AccountFieldupdate on Account (after update) {
List<Schema.FieldSetMember> trackedFields =     SObjectType.Account.FieldSets.alertengine.getFields();
if (trackedFields.isEmpty()) return;

List<Alert_vod__c> fieldChanges = new List<Alert_vod__c>();

List<string> apiNameList = new List<string>();        

if(Trigger.isUpdate){
for (Account aNew : trigger.new) {

Account aOld = trigger.oldmap.get(aNew.Id);

for (Schema.FieldSetMember fsm : trackedFields) {

String fieldName  = fsm.getFieldPath();
String fieldLabel = fsm.getLabel();

if (aNew.get(fieldName) != aOld.get(fieldName)) { // This line errors out

String oldValue = String.valueOf(aOld.get(fieldName));
String newValue = String.valueOf(aNew.get(fieldName));


Alert_vod__c aht = new Alert_vod__c();

aht.Field_Names__c = fieldName;
aht.Name = 'Account Verified:'+ aNew.Name;
aht.Activation_Date_vod__c = date.today();
aht.Expiration_Date_vod__c = date.today().addDays(15);
aht.Dismissible_vod__c = true;
aht.Alert_Text_vod__c = fieldName + ' changed from '+ oldValue + ' to '+ newvalue;


apiNameList.add(aht.Field_Names__c);
fieldChanges.add(aht);
}        
}
}
}
if (!fieldChanges.isEmpty()) {
insert fieldChanges;
}
}

Error:

Error: Invalid Data. Review all error messages below to correct your data. Apex trigger AccountFieldupdate caused an unexpected exception, contact your administrator: AccountFieldupdate: execution of AfterUpdate caused by: System.SObjectException: Invalid field PersonContact.AccountId for Account: Trigger.AccountFieldupdate

Can someone please help me here?

2

Field sets allow references to fields on related objects to be included. The FieldSetMember.getFieldPath method:

Returns a field path string in a format ready to be used in a dynamic SOQL query.

which for a related object is of the form relationshipName.fieldName.

If you really need to reference related object fields in your trigger you will have to query for them as triggers only provide the immediate fields of the object. But assuming you don't, your trigger can skip any FieldSetMember.getFieldPath values that include a dot to avoid the error you are getting:

for (Schema.FieldSetMember fsm : trackedFields) {

    String fieldName = fsm.getFieldPath();
    if (!fieldName.contains('.')) {
        ...
    }
}

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.