0
trigger VINfromAccountandContact on Case (before insert) {
    Set<id> setConids = new Set<id>();
    Map<id,id> mapAccidVsVIN = new Map<id,id>();
    for(Case c:trigger.new){
        if(c.Contactid <> NULL){
            setConids.add(c.Contactid); 
        }
    }
    if(!setConids.isEmpty()){
        for(Contact_Vehicle_Ownership__c cv :[SELECT id,Account_Name__c,Contact_Name__c,VIN_Lookup__r.id FROM Contact_Vehicle_Ownership__c WHERE Contact_Name__c IN:setConids]){
            mapAccidVsVIN.put(cv.Contact_Name__c, cv.VIN_Lookup__r.id);
        }
    }

    for(Case c:trigger.new){
        if(mapAccidVsVIN.containsKey(c.Contactid)){
            c.VIN__c = mapaccidVsVIN.get(c.Contactid);
        }
    }
}

I want to add this condition when accountid is not equal to Null can any one help how do i add this condition

2

Replacing line 5 of your trigger:

if(c.Contactid <> NULL){

with:

if(c.Contactid <> NULL && c.AccountId <> NULL){

or:

if (c.Contactid != null && c.AccountId != null) {

is the obvious answer to your question. If you are looking for something else - for example that the Contact's Account has to not be null as Cory describes - please be more specific in your question.

|improve this answer|||||
  • Just some background: I work for a Insurance company that does Service Cloud with VIN's and this trigger looks very similar to a trigger delivered froma contractor. I had to do a double look. :) Since I had to spend days refactoring the production code to scale and work. Probably colored my answer. :) Your answer is the simplest. ;) – CoryCowgill Nov 13 '14 at 1:34
  • @CoryCowgill Yeah my answer is the same as yours, but the case.AccountId != null point was a bit buried in your answer so I wasn't sure it would be picked up. On this forum, maybe starting with the simple "change this because of that" answer and adding further suggested changes after is the way to go. But yes which AccountId remains unclear... – Keith C Nov 13 '14 at 9:34
0

I would first highly advise that if this is production code you should not put any business logic in your Apex Trigger. Please see this article on Salesforce on how to write production quality triggers.

https://developer.salesforce.com/page/Trigger_Frameworks_and_Apex_Trigger_Best_Practices

Second instead of simply storing the VIN ID inside the Map I would store the entire SObject or result in the Map. Then you can be more flexible in processing your results.

Third not sure what you mean "accountid is not equal to null". There is AccountID on Contact and Case.

Do you want to check case? The field is case.AccountId, and you can just do case.AccountId != null in an expression.

|improve this answer|||||

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.