3

we want to get the source IP field from login history object. We do not know how to get it. We can get the IP but the system randomly chooses a one. Does anybody have any idea? thanks

trigger ProductBriefHistory on Product_Brief__c (after update) {
List<Schema.FieldSetMember> trackedFields = SObjectType.Product_Brief__c.FieldSets.PBHistoryTracking.getFields();
if (trackedFields.isEmpty()) return;


LoginHistory src = [SELECT SourceIp from LoginHistory WHERE UserId =:UserInfo.getUserId() Limit 1];

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

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

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

Product_Brief__c 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)) {

String oldValue = String.valueOf(aOld.get(fieldName));
String newValue = String.valueOf(aNew.get(fieldName));
if (oldValue != null && oldValue.length()>255) oldValue = oldValue.substring(0,255);
 if (newValue != null && newValue.length()>255) newValue = newValue.substring(0,255); 

 Product_Brief_History__c aht = new Product_Brief_History__c();
    aht.Product_Brief__c = aNew.Id;
aht.name__c         = fieldLabel;
aht.apiName__c   = fieldName;

aht.Updated_By__c = UserInfo.getUserId();
aht.OldValue__c  = oldValue;
 aht.NewValue__c  = newValue;
    aht.Source_IP__c = src.SourceIp;


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

}
  • What do you mean "the system randomly chooses one?" How do you know this? Do you have anything to back it up? – Adrian Larson Jun 18 '15 at 22:50
  • It does not give the latest Ip – Dananjaya Pathirana Jun 19 '15 at 14:07
6

One problem with your code is that LoginHistory can have many entries per UserId but your query of LoginHistory does not define the order and so does not define which entry you get.

If you want the latest entry then you need e.g.:

LoginHistory src = [
        select SourceIp
        from LoginHistory
        where UserId =:UserInfo.getUserId()
        order by LoginTime desc
        limit 1
        ];

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.