function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ajay ambatiajay ambati 

error in writing class

iam getting  this Error: Compile Error: Variable does not exist: account at line 10 column 3

public class my
{

public void my1()
{
list<schema.contact> lst = [Select id,name,account.name,account.Phone from contact where Phone=null];

for(contact c:lst)
{
  c.account.phone='9177818131';
   update c.account;
}
}
}
i will cal above method in anonymous block
Vivian Charlie 1208Vivian Charlie 1208

Hi Ajay,

 

I have modified your code a bit..

 

Please try the following code

 

public class my{

public void my1(){
    list<Account> lstAccount = new list<Account>();
    for(contact c:[Select id,name,account.name,account.Phone from contact where Phone=null]){
        Account objA = new Account(Id = c.AccountId);
        objA.phone = '9177818131';
        lstAccount.add(objA);
    }
    if(!lstAccount.isEmpty()){
        update lstAccount;
    }
}

 

 

Thanks 

Vivian

ajay ambatiajay ambati
i know this code but i need to know why i found error pls tel the solution
 
ajay ambatiajay ambati
this updating feild in account through parent to child relation ship query
 
Vivian Charlie 1208Vivian Charlie 1208

Hi Ajay,

 

As far as I know  you cannot update parent from the child accessing relationship fields. Since in order to update the parent Salesforce needs an instance of the record that needs to be updated, i.e reference to some concrete sobject. If you try updating any parent field from the child itself it results in an exception "attempt to de-reference a null object"

 

Thanks

Vivian

Vivian Charlie 1208Vivian Charlie 1208

Hi Ajay,

 

Even if what you have written updates the parent this methods WILL FAIL in the future if there was a bulk operation.

 

Salesforce has a DML limit of 150 statements and with the current implementation where you update the Account in the for loop itself the code WILL FAIL the day your query returns 151 records.

 

As per best practice please update your code inorder to remove the update statement from the for loop, which leaves you with the solution I suggested.

 

Thanks

Vivian