Search code examples
salesforceapexsoql

SObject row was retrieved via SOQL without querying the requested field error is not coming


This trigger is first inserting related contact when account is inserted and then updating a custom field on Account name 'Client_Contact__c' with inserted contact lastname.

trigger practicetrigger on Account ( after insert ) {
        if ( Trigger.isinsert && Trigger.isafter ) {
           Set<Id> accId = new Set<Id>();
           list<Contact> conList = new list<Contact>();
           list<Account> accToUpdate = new list<Account>();
           map<Id, Account> accMap = new map<Id, Account>();
        for ( Account a : Trigger.New ) {
           Contact c = new Contact( LastName = a.Name, AccountId=a.Id );
           conList.add ( c );
           accId.add( a.Id );
        }
        if ( !conList.isempty() ) {
           insert conList;
        }
        for ( Account ac : **[select Id from Account where Id =: accId]** ) {
           ac.Client_Contact__c = ' new contact ';
           system.debug( 'Account ac '+ac.Client_Contact__c);
           accMap.put( ac.Id , ac );
        }
        if ( conList.size() > 0 ) {
           for ( Contact con : conList ) {
               if ( accMap.containskey( con.AccountId ) ) {
                    accMap.get( con.AccountId ).Client_Contact__c = con.lastname;
                    System.debug( ' accMap '+accMap.get(con.AccountId));
                    accToUpdate.add( accMap.get(con.AccountId) );
               }
           }
        }
        if ( !accToUpdate.isempty() ) {
           update accToUpdate;
        }
       }
    }

In the bold part of code, I have not queried the custom field Client_Contact__c but still error is not coming and code is executing successfully. Why error is not coming? Can anybody tell what i am missing here and In what situation this error do not come?


Solution

  • You can always set a field to new value even if you didn't query it. Not sure what you think the problem is?

    In a normal database and SQL you can do UPDATE TABLE Users SET Name = 'Joe' WHERE Id = 123, why something similar shouldn't be possible in Apex? With different syntax, yes - but still, same idea?