+ Start a Discussion
Nico AnicaNico Anica 
Hello, 
I am trying to display some information but everytime I have this following message error :
SObject row was retrieved via SOQL without querying the requested field: Contact.Client_a_risque__c

Here below is my code : 

<!--*********************************************************************************
Class Name      : CCF_CustomContactSearch
Description     : This page will be open by InIn on an Agent's browser, once a Case is 
                  assigned to the Agent. 
                  When loaded, the page will contain a list of Contacts 
                  possibly matching to a value (svalue) contained in the URL as a parameter
                  The Agent also has the option to search for a specific contact, using the
                  input field beside "Search Contact" button. The value provided in the input 
                  field will be searched in ALL fields in the Contact Object
                  For every listed Contact, the Agent has the option lo link it to the Case,
                  using "Link to Case" button
Created By      : Mihai JURIAN
Created Date    : 30-Jan-17
Modification Log:
================================================================================== 
Developer                   Date                   Description
==================================================================================        
Mihai Jurian            30-Jan-17                   Initial Version
*********************************************************************************-->
<apex:page controller="CCF_searchContactController" docType="html-5.0" action="{!search_onLoad}" title="{!$Label.InIn_Recherche_de_contact}">

    <apex:includeScript value="/support/console/28.0/integration.js"/>
    <script type="text/javascript">
        function openCaseDetails() {
            sforce.console.openPrimaryTab(undefined, '/{!caseId}', true, '{!caseNumber}');
            closeTab();
        }

        // The callback function that closeTab will call once it has the ID for its tab
        var callCloseTab = function callCloseTab(result) {
            sforce.console.closeTab(result.id);
        }
    
        function closeTab() {
            sforce.console.getEnclosingPrimaryTabId(callCloseTab);
        }
    
        var pageLoad = window.onload;
        window.onload = function() 
        {
            if (pageLoad) 
            {
                pageLoad();
            }
            sforce.console.setTabTitle('{!$Label.InIn_Recherche_de_contact}');
        }
    </script>
    <apex:form >
        <apex:actionFunction name="updateSortOrderBy1" action="{!updateSortOrderBy}">
            <apex:param id="updateOrderBy" name="updateOrderBy" value="" />
        </apex:actionFunction>
        <apex:actionFunction name="search_method" action="{!search_method}" />

        
        <apex:input value="{!searchValue}" id="searchValue"/>
        <apex:commandButton value="{!$Label.InIn_Trouver_le_Contact}" onclick="search_method(); return false;" />
        <apex:outputText id="searchWarning" value="Please enter at least 2 characters before searching." rendered="{!showSearchWarning}" />
        
       
        <apex:pageBlock title="Contacts" id="block">
            <apex:inputCheckbox value="{!excludeHasFilter}"  onclick="search_method();" />
            <apex:outputText >{!$Label.CCF_CustomSearch_IncludeAllRecords}</apex:outputText>
            <br/>&nbsp;
            <apex:pageMessages />
            <!-- the Pagination/Navigation buttons -->
            <apex:pageBlockButtons rendered="{!RenderNavigation}" location="bottom"> 
                <apex:commandButton value="{!$Label.navigationFirst}" action="{!first}" disabled="{!DisablePrevious}"/>
                <apex:commandButton value="{!$Label.navigationPrevious}" action="{!previous}" disabled="{!DisablePrevious}"/>
                <apex:commandButton value="{!$Label.navigationNext}" action="{!next}" disabled="{!DisableNext}"/>
                <apex:commandButton value="{!$Label.navigationLast}" action="{!last}" disabled="{!DisableNext}"/>
            </apex:pageBlockButtons>
            <!-- the table showing the Contacts -->
            <apex:pageblockTable id="contactList" value="{!conListToShow}" var="con">
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!$ObjectType.Contact.fields.Name.Label + IF(orderBy == 'Name', '▼', IF(orderBy == 'Name DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="Name" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputLink value="/{!con.Id}" id="theLink">{!con.name}</apex:outputLink>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!$ObjectType.Contact.fields.Birthdate.Label + IF(orderBy == 'Birthdate', '▼', IF(orderBy == 'Birthdate DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="Birthdate" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputfield value="{!con.Birthdate}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!$ObjectType.Contact.fields.Phone_1__c.Label + IF(orderBy == 'Phone_1__c', '▼', IF(orderBy == 'Phone_1__c DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="Phone_1__c" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputfield value="{!con.Phone_1__c}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!$ObjectType.Contact.fields.Phone_2__c.Label + IF(orderBy == 'Phone_2__c', '▼', IF(orderBy == 'Phone_2__c DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="Phone_2__c" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputfield value="{!con.Phone_2__c}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!$ObjectType.Contact.fields.Phone_3__c.Label + IF(orderBy == 'Phone_3__c', '▼', IF(orderBy == 'Phone_3__c DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="Phone_3__c" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputfield value="{!con.Phone_3__c}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!$ObjectType.Contact.fields.Email_1__c.Label + IF(orderBy == 'Email_1__c', '▼', IF(orderBy == 'Email_1__c DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="Email_1__c" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputfield value="{!con.Email_1__c}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!$ObjectType.Contact.fields.Email_2__c.Label + IF(orderBy == 'Email_2__c', '▼', IF(orderBy == 'Email_2__c DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="Email_2__c" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputfield value="{!con.Email_2__c}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!$ObjectType.Contact.fields.Agency_PIN__c.Label + IF(orderBy == 'Agency_PIN__c', '▼', IF(orderBy == 'Agency_PIN__c DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="Agency_PIN__c" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputfield value="{!con.Agency_PIN__c}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!'Record Type' + IF(orderBy == 'RecordType.Name', '▼', IF(orderBy == 'RecordType.Name DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="RecordType.Name" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputfield value="{!con.RecordType.Name}"/>
                </apex:column>
                <apex:column >
                    <apex:facet name="header">
                        <apex:commandLink action="{!updateSortOrderBy}" value="{!$ObjectType.Contact.fields.Client_a_risque__c.Label + IF(orderBy == 'Client_a_risque__c', '▼', IF(orderBy == 'Client_a_risque__c DESC', '▲', ''))}" >
                            <apex:param name="updateOrderBy" value="Client_a_risque__c" assignTo="{!updateOrderBy}"/>
                        </apex:commandLink>
                    </apex:facet>
                    <apex:outputfield value="{!con.Client_a_risque__c}"/>
                </apex:column>
                <!-- the buttons "Link to Case" -->
                <apex:column headervalue="{!$Label.Link_to_Case}">
                    <apex:commandButton value="{!$Label.Link_to_Case}" action="{!linkContactToCase}" rerender="block" oncomplete="openCaseDetails()">
                        <apex:param name="theContactId" value="{!con.Id}" assignTo="{!contactId}"/>
                    </apex:commandButton>
                </apex:column>
            </apex:pageblockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>


THANK YOU VERY MUCH FOR YOUR HELP.
Best Answer chosen by Nico Anica
Deepali KulshresthaDeepali Kulshrestha
Hi Nico,

You are getting this error because you are not querying this field 'Client_a_risque__c' which is in your Contact Object.
If Contact is your parent object then you should use this 'Contact.Client_a_risque__c' in your query in Controller named 'CCF_searchContactController'.

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com
Angela DomingoAngela Domingo 
I am working on Admin Beginner Lightning Experience Customization Set Up Your Org module (https://trailhead.salesforce.com/trails/force_com_admin_beginner/modules/lex_customization/units/lex_customization_custom_objects?trailmix_creator_id=00550000006yDdKAAU&trailmix_id=prepare-for-your-salesforce-administrator-credential) and have completed all the steps to create the objects and when clicking on the "check challenge" button, it returns the error: "Challenge Not yet complete... here's what's wrong: Could not find the 'Audit_Notes__c' field on the custom object named 'Energy_Audit__c'."
Screenshot of verification error in Trailhead for Set Up Your Org module

I have gone back into the Trailhead Playground that I used and verified that the field does exist and is related and on the custom object as I had set it up.
Energy Audit Object screenshot
Screenshot of Audit Notes related field

I can't get past this challenge and it won't complete this module unless it is verified. Is anyone else running into this?  I have successfully had all the previous challenges completed and this is the first time I got an error that I can't figure out what is missing.

Thanks in advance for your help.
Angela
Best Answer chosen by Angela Domingo
bretondevbretondev
Check that FLS is correct for the field

User-added image
Also make sure the field is on all your Energy Audit page layouts
Sean GibsonSean Gibson 
Hi,

I am fairly new to salesforce as an admin, I am looking for a bit of advice around a formula field,

I have a field which converts a date/time value and takes only the date bu converting it to text, however the format of the date is YYYY-MM-DD, I am wondering if there is any way to change the order of the date field so it shows DD-MM-YYYY

My formula is below;

Name&" - "&ProductCode__r.Name&" - "&LEFT(TEXT(Outward_Date__c),FIND(" ",TEXT(Outward_Date__c))-1)&" - "& From__r.Name&" >> "&To__r.Name

Appreciate any help I can be offered,

Thank you,
Best Answer chosen by Sean Gibson
Ajay K DubediAjay K Dubedi
Hi Sean,

I looked at your issue and found the solution. I tested it at my org and it worked.
You have one formula field-
Date field will be in  DD-MM-YYYY format by this solution.

Replace Your code with this->

Name&" - "&ProductCode__r.Name&" - " & Right(TEXT(Outward_Date__c),2) &"-"& RIGHT(LEFT(TEXT(Outward_Date__c),7),2) &"-"& LEFT(TEXT(Outward_Date__c),4) &" - "& From__r.Name&" >> "&To__r.Name


This piece of formula will write the date in DD-MM-YYYY format.

 Right(TEXT(Outward_Date__c),2) &"-"& RIGHT(LEFT(TEXT(Outward_Date__c),7),2) &"-"& LEFT(TEXT(Outward_Date__c),4)


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com
Malik Butler 5Malik Butler 5 
I have an issue in the debug section it's saying that the ParentRecordType is an unexpected token for service appointments. 
global class ServiceAppointmentCancel implements Database.Batchable<SObject>, Schedulable
{ 
    global Database.QueryLocator start(Database.BatchableContext BC) 
    { 
        String subject = 'Reload,Pre-Trip report,Post-Trip report'; 
        String status = 'O'; 
        Date SchedEndTime = Date.today();
        String ParentRecordType = 'Work Order';
        String ID = 'WorkOrder.ID';
        String query = 'SELECT Subject,Status,SchedEndTime FROM ServiceAppointment WHERE subject = :subject AND status = :status AND SchedEndTime < :SchedEndTime' + 'SELECT ParentRecordType, FROM ServiceAppointment WHERE ParentRecordType = :ParentRecordType AND ID = ID'; 
        return Database.getQueryLocator(query); 
    } 

    global void execute(Database.BatchableContext BC, List<WorkOrder> serviceAppointments) 
    { 
        // Loop to iterate over the service appointments 
        for(WorkOrder service : serviceAppointments)
        
        { 
            service.status = 'C';
        } 
        for(WorkOrder work : serviceAppointments)
        {
            work.status = 'C';
        }
        // Preforming the DML operation 
        update serviceAppointments;
    } 

    global void finish(Database.BatchableContext BC) 
    { } 

    global void execute(System.SchedulableContext SC) 
    { 
        Database.executeBatch(new ServiceAppointmentCancel(), 200); 
    } 
}
Best Answer chosen by Malik Butler 5
Dhanya NDhanya N
Hi Malik,

In this query, no need to concat 2 soql.
'SELECT Subject,Status,SchedEndTime FROM ServiceAppointment WHERE subject = :subject AND status = :status AND SchedEndTime < :SchedEndTime' + 'SELECT ParentRecordType, FROM ServiceAppointment WHERE ParentRecordType = :ParentRecordType AND ID = ID';

Instead add all the conditions in same soql:
'SELECT Subject,Status, SchedEndTime, ParentRecordType FROM ServiceAppointment WHERE subject = :subject AND status = :status AND SchedEndTime < :SchedEndTime AND ParentRecordType = :ParentRecordType AND ID = ID';


Thanks,
Dhanya 
Best Answer chosen by Admin (Salesforce Developers) 
Vinita_SFDCVinita_SFDC

Hello,

 

You can create an email template in a test class as we create in any apex class like:

 

EmailTemplate e = new EmailTemplate (developerName = 'test', FolderId = 'Give Id Of Email Folder', TemplateType= 'Text', Name = 'test'); // plus any other fields that you want to set

insert e;
 
Best way to create a custom email template is to create visualforce email templates. Please note that you can not sent emails from test calss.
Filip Poverud 4Filip Poverud 4 
Build a Conference Management App --> Create an Aura Component

I have tried to Copy/Paste using CTRL+C and CTRL+V, using the mouse copy/paste functions and also writing the code manually but all attempts fail. Are there any other ways of copying the text so I can complete this challenge ?
Best Answer chosen by Filip Poverud 4
Filip Poverud 4Filip Poverud 4
I fixed the error by using:
 
e.force:navigateToObjectHome

Instad of:
"standard__objectPage"

For some reason it was the navigation back to the record that failed using the code in the module.
Tom DawsonTom Dawson 
Hi All

I'm trying to access field values from an object related to the initial one in the call. Our relationship is as follows:

Contact --> Post Fulfillment --> Post

I am trying to use an iteration to get values from Post when the initial call is to Contact. See code below:

Apex:
@AuraEnabled
    public static List<Contact> getHSList(){
        List<Contact> myHSList = new List<Contact>();
        myHSList = [Select Id, 
                    Name, 
                    Fire_Warden__c,
                    Phone,
                    (SELECT id, Post__c,Post__r.Area__c, Post__r.Floor__c, Post__r.Section__c
                     FROM Contact.Post_Fulfillments__r)
                    From Contact
                    Where Fire_Warden__c = true];
        return myHSList;
    }
Controller
({
    onInit : function(component, event, helper) {
        
        console.log('onInit');
        
        var action = component.get("c.getHSList");
        
        action.setCallback(this, function(a) {
            
            var HandSData = a.getReturnValue();
            console.log(HandSData);
            component.set("v.contactList",HandSData);
            console.log(HandSData.length);
            
        });
        $A.enqueueAction(action);
    }
    
})
Component
<aura:Iteration items="{!v.contactList}" var="con" >
                <tr class="slds-hint-parent">
                    <th data-label="Name" scope="row">
                        <div class="slds-truncate" title="Cloudhub">{!con.Name}</div>
                    </th>
                    <td data-label="Phone">
                        <div class="slds-truncate" title="Cloudhub">{!con.Phone}</div>
                    </td>
                    <td data-label="Close Date">
                        <div class="slds-truncate" title="4/14/2015">{!con.Post_Fulfillments__r.Post__r.Floor__c} place</div>
                    </td>
                </tr>
            </aura:Iteration>

I am able to access both Name and Phone from the contact. I can also see from the Chrome inspector that the field values for Location are coming through, I just cannot access them. 

As you can see i have tried 
{!con.Post_Fulfillments__r.Post__r.Floor__c}
But it doesnt seem to work.

Any help would be great.

Thanks

Tom 


 
Best Answer chosen by Tom Dawson
Soyab HussainSoyab Hussain
Hi Tom Dawson,

We you can't do this, because con.Post_Fulfillments__r this one is an another list.

Incorrect
{!con.Post_Fulfillments__r.Post__r.Floor__c}

Correct
{!con.Post_Fulfillments__r[0].Post__r.Floor__c}

Or we can use another <aura:Iteration> inside the <aura:Iteration> like this.
<aura:Iteration items="{!v.contactList}" var="con" >
                <tr class="slds-hint-parent">
                    <th data-label="Name" scope="row">
                        <div class="slds-truncate" title="Cloudhub">{!con.Name}</div>
                    </th>
                    <td data-label="Phone">
                        <div class="slds-truncate" title="Cloudhub">{!con.Phone}</div>
                    </td>
                    <td data-label="Close Date">
                        <div class="slds-truncate" title="4/14/2015">
                             <aura:Iteration items="{!con.Post_Fulfillments__r}" var="post" >
                                    {!post.Post__r.Floor__c} 
                            </aura:Iteration> place</div>
                    </td>
                </tr>
            </aura:Iteration>



Regards,
Soyab
 
phil.vaseyphil.vasey 

Hi

 

I'm new to this so please forgive my ignorance.

 

I'm getting the exception when:

 

  1. insert an Opportunity
  2. insert a ContentVersion
  3. post the new ContentVersion to the Opportunity's chatter feed
  4. delete the Opportunity

Does anybody know why, and if so, how to overcome the exception?

 

I am using API version 26.0

 

Thanking you in advance

 

 

private static void TestOpportunityDeletion()

{
  // create an opportunity
  Opportunity opp = new Opportunity() ;
  opp.Name = 'Test Name' ;
  opp.StageName = 'Test Stage Name' ;
  opp.CloseDate = Date.Today() ;
  insert opp ;

  // attach a document to its chatter feed
  ContentVersion doc = new ContentVersion() ;
  doc.Title = 'Test Version' ;
  doc.PathOnClient = 'test version.docx' ;
  doc.VersionData = Blob.ValueOf( 'test content' ) ;
  doc.Origin = 'H' ;
  insert doc ;

  FeedItem post = new FeedItem() ;
  post.Type = 'ContentPost' ;

  post.ParentID = opp.Id ;
  post.RelatedRecordID = doc.id ;
  insert post ;

 

  // delete the opportunity
  delete opp ;
}

Best Answer chosen by Admin (Salesforce Developers) 
Jia HuJia Hu
Before ' delete opp ;' add
delete post;

Then your code will work.
Glenn Dailey 1Glenn Dailey 1 
The 'AccountProcessor' class did not achieve 100% code coverage via your test methods. Make sure that you chose 'Run All' tests in the Developer Console at least once before attempting to verify this challenge. I did the run all with no luck. I did notice that this is the new section that was just added and I ran into issues in the first unit too.

Create an Apex class with a method using the @future annotation that accepts a List of Account IDs and updates a custom field on the Account object with the number of contacts associated to the Account. Write unit tests that achieve 100% code coverage for the class.
Create a field on the Account object called 'Number_of_Contacts__c' of type Number. This field will hold the total number of Contacts for the Account.
Create an Apex class called 'AccountProcessor' that contains a 'countContacts' method that accepts a List of Account IDs. This method must use the @future annotation.
For each Account ID passed to the method, count the number of Contact records associated to it and update the 'Number_of_Contacts__c' field with this value.
Create an Apex test class called 'AccountProcessorTest'.
The unit tests must cover all lines of code included in the AccountProcessor class, resulting in 100% code coverage.
Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.

public class AccountProcessor
{
  @future
  public static void countContacts(Set<id> setId)
  {
      List<Account> lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
      {
          List<Contact> lstCont = acc.contacts ;
         
          acc.Number_of_Contacts__c = lstCont.size();
      }
      update lstAccount;
  }
}

and
@IsTest
public class AccountProcessorTest {
    public static testmethod void TestAccountProcessorTest(){
        Account a = new Account();
        a.Name = 'Test Account';
        Insert a;

        Contact cont = New Contact();
        cont.FirstName ='Bob';
        cont.LastName ='Masters';
        cont.AccountId = a.Id;
        Insert cont;
       
        set<Id> setAccId = new Set<ID>();
        setAccId.add(a.id);
 
        Test.startTest();
            AccountProcessor.countContacts(setAccId);
        Test.stopTest();
       
        Account ACC = [select Number_of_Contacts__c from Account where id = :a.id LIMIT 1];
        System.assertEquals ( Integer.valueOf(ACC.Number_of_Contacts__c) ,1);
  }
 
}
Best Answer chosen by Glenn Dailey 1
Amit Chaudhary 8Amit Chaudhary 8
I am glad that works. PLease mark best answer and close this thread so that if some one has same issue that post can help other
Timothy SmithTimothy Smith 
My company's org has about five triggers more than one existing (after insert, after edit).  I am about to create an (after insert) trigger.  Suggestions as to how I would consolidate or should I create my trigger and add to the pile.  If I should consolidate, how would that look?
Best Answer chosen by Timothy Smith
Deepali KulshresthaDeepali Kulshrestha
Hi Timothy,

1.You can see the best practice to write trigger from the below link:-

https://developer.salesforce.com/index.php?title=Apex_Code_Best_Practices&oldid=26951

2.Trigger Best Practices | Sample Trigger Example | Implementing Trigger Framework

 1) One Trigger Per Object
 A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts

 2) Logic-less Triggers
 If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

 3) Context-Specific Handler Methods
 Create context-specific handler methods in Trigger handlers

 4) Bulkify your Code
 Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

 5) Avoid SOQL Queries or DML statements inside FOR Loops
 An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception

 6) Using Collections, Streamlining Queries, and Efficient For Loops
 It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits

 7) Querying Large Data Sets
 The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and queryMore

 8) Use @future Appropriately
 It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found

 9) Avoid Hardcoding IDs
 When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail
Trigger Example:

 trigger AccountTrigger on Account( after insert, after update, before insert, before update)

{

 

    AccountTriggerHandler handler = new AccountTriggerHandler(Trigger.isExecuting, Trigger.size);

     

    if( Trigger.isInsert )

    {

        if(Trigger.isBefore)

        {

            handler.OnBeforeInsert(trigger.New);

        }

        else

        {
            handler.OnAfterInsert(trigger.New);

        }

    }

    else if ( Trigger.isUpdate )

    {

        if(Trigger.isBefore)

       {

            handler.OnBeforeUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);

        }

        else

        {

            handler.OnAfterUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);

        }

    }

Apex Class for trigger:-

public with sharing class AccountTriggerHandler
{

    private boolean m_isExecuting = false;
    private integer BatchSize = 0;
    public static boolean IsFromBachJob ;
    public static boolean isFromUploadAPI=false;

    public AccountTriggerHandler(boolean isExecuting, integer size)

    {

        m_isExecuting = isExecuting;
        BatchSize = size;

    }

    public void OnBeforeInsert(List<Account> newAccount)

    {
        system.debug('Account Trigger On Before Insert');

    }

    public void OnAfterInsert(List<Account> newAccount)

    {
        system.debug('Account Trigger On After Insert');

    }

    public void OnAfterUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On After Update ');

        AccountActions.updateContact (newAccount);

    }

    public void OnBeforeUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {

        system.debug('Account Trigger On Before Update ');

    }

 
  @future
    public static void OnAfterUpdateAsync(Set<ID> newAccountIDs)
    {

    }     

    public boolean IsTriggerContext

    {

        get{ return m_isExecuting;}

    }
    public boolean IsVisualforcePageContext

    {

        get{ return !IsTriggerContext;}

    }

     

    public boolean IsWebServiceContext

    {

        get{ return !IsTriggerContext;}
    }
    public boolean IsExecuteAnonymousContext

    {

        get{ return !IsTriggerContext;}

    }

}

Create one Trigger Action Class

public without sharing class AccountActions
{
    public static void updateContact ( List<Account> newAccount)
    {
        // Add your logic here
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com