Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I am trying to default the Account Name in a case to 'abc corp' but while executing the code, it gives the error

Attempt to de-reference a null object. its happening at line 10 which c.account.name = defaultAcc.Id

.

The code

trigger DefaultAccName on Case(after insert, after update) {

    Account defaultAcc = [
        SELECT Id
        FROM Account
        WHERE Name ='abc corp'];

for (Case c: trigger.New) {

    if (defaultAcc.Id != null)
     { 
      if(c.Type=='Internal')
         {
           c.account.name = defaultAcc.Id;
         }
         }
    }
}

Any help in resolving this is appreciated.

Deepak

share|improve this question

1 Answer 1

up vote 4 down vote accepted

In a trigger, "related" objects aren't automatically queried; this means you can't use c.account.name without first querying it. Also, if you're trying to update the account's name, you'd need a DML operation. Based on your code, I'd assume you meant AccountId instead:

if(c.Type=='Internal') {
    c.AccountId = defaultAcc.Id;
}

Also, this must be a "before insert, before update" trigger, or you'll get a "read-only record" error.

share|improve this answer
    
Hi i am trying to update the Account name (which is a lookup field) in the case object. –  deepak nagarajachary Apr 25 at 5:10
    
@deepaknagarajachary just follow above code you will get what you are expecting. –  snehakem Apr 25 at 5:29
    
Double thumbs up.. Yes it worked after i made the above change. Thank you for all your help on this. –  deepak nagarajachary Apr 25 at 9:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.