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

1 Answer 1

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.

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .