0

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

4

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.

| 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 '14 at 5:10
  • @deepaknagarajachary just follow above code you will get what you are expecting. – snehakem Apr 25 '14 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 '14 at 9:00

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.