Wednesday, 14 November 2018

Basic Pagination with Custom Controller



VF Code:

<apex:page controller="PaginationWithCustomControllerClass">
    <apex:form >
        <apex:pageBlock title="Pagination with Custom Controller
" id="pgBlock">
            <apex:pageBlockTable value="{!Accounts}" var="acc" id="pgTable">
                <apex:column value="{!acc.Name}"/>
                <apex:column value="{!acc.Industry}"/>
                <apex:column value="{!acc.Rating}"/>
                <apex:column value="{!acc.Phone}"/>
            </apex:pageBlockTable>
            <br/>
            <b><apex:outputText value="Total Number of Records are {!totalrecords}"/> </b>
       
            <apex:pageBlockButtons >
                <apex:commandButton value="Previous" action="{!Previous}" rerender="pgBlock"
                                    status="status" disabled="{!DisablePrevious}" />
                <apex:commandButton value="Next" action="{!Next}" reRender="pgBlock"
                                    status="status" disabled="{!DisableNext}" />
                <apex:actionStatus id="status" startText="Loading..."/>
             

            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>

</apex:page>




Controller Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public with sharing class PaginationWithCustomControllerClass{

    private Integer CountTotalRecords;
    private Integer OffsetSize = 0;
    private Integer QueryLimit = 10;
    public list <Account> lstAccount{get;set;}
    
    public PaginationWithCustomControllerClass(){
        CountTotalRecords= [select count() from Account];
    }
      
    public list <Account> getAccounts(){
        lstAccount = new list  <Account> ();
        lstAccount = [Select id, Name, Industry, Rating, Phone from Account order by Name limit :QueryLimit offset :OffsetSize];
        return lstAccount; 
    }
    
    public PageReference Next() {
        OffsetSize += QueryLimit;
        return null;
    }
    
    public PageReference Previous() {
        OffsetSize -= QueryLimit;
        return null;
    }
  
    public Boolean getDisablePrevious(){
        if(OffsetSize>0){
            return false;
        }else {
            return true;
        }
    }
    
    public Boolean getDisableNext() {
        if (OffsetSize + QueryLimit < countTotalRecords){
            return false;
        }else {
            return true;
        }
     }
    
    public integer gettotalrecords(){
        return [select count() from Account];
    }
}

Create Given Number of Child records On Parent Creation


Let's say In Account there is a custom field called NumberofContacts__c(Number Data Type). While we are creating an Account, if we give the NumberofContacts__c as '5' then this trigger will be automatically creates 5 contact records.

NOTE: We can give the number up to 10,000 since the Governer Limits fire the following error.

System.LimitException: Too many DML rows: 10001

.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
trigger CreateGivenNoOfContacts on Account (After Insert) {
    Map<Id,Decimal>AccLocMap =New Map<Id,Decimal>();
    List<Contact>ConInsert = New List<Contact> ();
    for(Account acc : trigger.new){
        AccLocMap.put(acc.Id,acc.NumberofContacts__c);
    }
    
    for(Account acc : trigger.new){

        for(integer i=0; i<AccLocMap.get(acc.id); i++){
            contact con = New Contact();
            con.LastName = acc.Name + ' Contact';
            con.AccountId = acc.Id;
            ConInsert.add(con);
        }
    }
    
    Insert ConInsert;
        
}

Trigger to Delete Child On Deletion of Parent


This trigger is to Delete the Child Records on Delete of Parent Record
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
trigger DeleteContact on Account (After Delete) {
    Set<Id>AccIdSet = New Set<Id>();
    List<Contact> ConDelList = New List<Contact>();
    
    for(Account acc : trigger.old){
        AccIdSet.add(acc.id);
    }
    
    for(contact con : [Select Id, AccountId from Contact WHERE AccountId In : AccIdSet]){
        ConDelList.add(con);
    }
    
    Delete ConDelList;
}

Sunday, 11 November 2018

Trigger to Create Child on insert of Parent


This trigger to create Contact(Child) automatically on insertion of Account(Parent)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
trigger CreateContact on Account (after insert) {
    
    List<contact> ConList = New List<Contact>();
    
    for(Account Acc : Trigger.New){
        Contact con = New Contact();
        con.LastName = Acc.Name + ' Contact';
        con.AccountId = Acc.Id;
        ConList.add(con);
    }
    
    if(ConList.Size()>0 && !(ConList.isEmpty()))
        insert ConList;
}

Trigger to update child field with parent field


This trigger is to update the Child field with Parent field. In the below example, we will be updating the Contact's LastName with Account's Name.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
trigger UpdateChildWithParent on Contact (Before insert, before update) {
 
    Set<id> AccId = New Set<id>();
    Map<Id,Account> AccountMap = New Map<Id,Account>();

    
    For(contact contact : trigger.new){
        AccId.add(contact.AccountId);
    }
    
    for(Account acc : [Select Id,Name from Account WHERE ID IN : AccId]){
        AccountMap.put(acc.Id,Acc);
    }

    For(contact contact : trigger.new){
        if(AccountMap.containsKey(Contact.AccountId)){
            contact.LastName = AccountMap.get(contact.AccountId).Name;
        }
    }

}

Thursday, 1 November 2018

How To Fetch Anniversary Records for a Selected Record

Hello..!!

Today We will be Discussing about writing SOQL to fetch Anniversary records.

Scenario:

I have an opportunity with some CloseDate (9/3/2015).
Now by writing SOQL, I need to fetch the records of last five years opportunity record where the CloseDate as Same as the selected Opportunity Record (i.e., 9/3)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Date fromDate = [Select Id, CloseDate from Opportunity WHERE ID = '0066F00000v4dB2'].CloseDate;



integer startYear = fromDate.addYears(-5).year();

integer thisMonth = fromDate.month();

integer thisDay = fromDate.day();

system.debug('*****'+startYear);

system.debug('---'+[Select Id, CloseDate from Opportunity WHERE 

                    CALENDAR_MONTH(CloseDate)=:thisMonth  AND 

                    CALENDAR_YEAR(CloseDate)>=:startYear AND 

                    DAY_IN_MONTH(CloseDate) =: thisDay]);


 This query will return the Following results

Sunday, 16 September 2018

Trigger for All Rollup Summary calculations on Lookup Relation- Count, Minimum, Maximum, Sum and Average

This trigger will help you to update all the Rollup Summary calculations on Look up RelationShip.

Objects and Fields Information :
Contact (Object) --> Amount__c(Custom Field)
Account (Object) --> Sum__c (Custom Field)
                            --> Avg__c (Custom Field)
                           --> Min__c (Custom Field)
                           --> Max__c (Custom Field)
                           --> Count__c (Custom Field)

Here we are updating all the Account fields based on Contact's Amount__c Field data


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
trigger FullRollup on Contact (after insert, after update, after delete, after undelete){
   
    set<Id>Parent_set = new set<id>();
    List<Account>AccUpdateList = New List<Account>();
   
    if(trigger.isdelete || trigger.isupdate){
        for(Contact con : Trigger.old){
            Parent_set.add(con.AccountId);
        }
    }
   
    if(trigger.isInsert || trigger.isUpdate || trigger.isUndelete){
        for(Contact con : Trigger.New){
            Parent_set.add(con.AccountId);
        }
    }
   
   
    for(AggregateResult aggcon : [Select AccountId,
                                      Count(Id)countt, Sum(amount__c)summ, avg(amount__c)avgg, min(amount__c)minn, max(amount__c)maxx
                                      From contact Where AccountId IN :Parent_set Group By AccountId]){
        Account Acc = New Account();
        Acc.Id     = (Id)aggcon.get('AccountId');
        Acc.Sum__c = (Decimal)aggcon.get('summ');
        Acc.Avg__c = (Decimal)aggcon.get('avgg');
        Acc.Min__c = (Decimal)aggcon.get('minn');
        Acc.Max__c = (Decimal)aggcon.get('maxx');
        Acc.Count__c = (Decimal)aggcon.get('countt');  
       
        AccUpdateList.add(Acc);    
       
    }
    Update AccUpdateList;
   
}