• Amit Jadhav 13
  • NEWBIE
  • 140 Points
  • Member since 2019

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 20
    Questions
  • 23
    Replies
I am new when it comes to visualforce and creating custom controllers. 

I have a problem to solve where each Account needs the ability to quickly add an Invoice with only 1 Invoice line item. The ask is to be able to click a button on the Account and be prompted to enter the quantity prior to creating the invoice. 
The result should be after the quantity is entered, an Invoice record is created with 1 Invoice line item showing the fields price and quantity.

Help with how the code should be written would help a lot.

 
class :
public class RevertQuantityTriggerHandler {
    //public static Boolean runOnce = true;
    //RevertQuantityHelperClass helpobj = new RevertQuantityHelperClass();
    public List<Inventory__c> lstofinventory = new List<Inventory__c>([select id,Name,Inventory_Name__c,Account__c,Quantity__c,Product__c from Inventory__c]);
    Double difference;
    public double oldTotalQuantity, newTotalQuantity;
    
    public void onBeforeDelete(List<Cost_Price__c> listofcostprice)
    {
        
        for(Cost_Price__c obj : listofcostprice)
        {
            System.debug('cost Price --->'+obj);
            for(Inventory__c inventobj : lstofinventory)
            {
                
                if(obj.Product_From_Inventory__c == inventobj.id)
                {
                    inventobj.Quantity__c += obj.Quantity__c;
                }
                
            }
            update lstofinventory;
        }
    }
    
    public void onAfterUpdate(List<Cost_Price__c> listofcostprice, List<Cost_Price__c> triggerold)
    {
     	for(Cost_Price__c cp:listofcostprice )
        {
            system.debug('listofcostprice'+listofcostprice);
            newTotalQuantity=cp.Quantity_Per_Container__c*cp.Total_of_Containers__c; 
        }
        for(Cost_Price__c cp:triggerold )
        {
            system.debug('triggerold'+triggerold);
            oldTotalQuantity=cp.Quantity_Per_Container__c*cp.Total_of_Containers__c; 
        }
        
        if(triggerold[0].Product_From_Inventory__c != null)
        {
            
            if((oldTotalQuantity != null || oldTotalQuantity != 0) && (newTotalQuantity != null || newTotalQuantity != 0) )
            {
                //changed this if condition
                if(listofcostprice[0].Product_From_Inventory__c==triggerold[0].Product_From_Inventory__c)
                {
                    
                    for(Cost_Price__c obj : listofcostprice)
                    {
                        
                        if(listofcostprice[0].id ==  triggerold[0].id)
                        {
                            system.debug('newTotalQuantity'+newTotalQuantity);
                            system.debug('oldTotalQuantity'+oldTotalQuantity);
                            if(newTotalQuantity > oldTotalQuantity)
                            {
                                
                                //Calculate difference between new total quantity and old total quantity
                                difference = newTotalQuantity - oldTotalQuantity;
                                system.debug('diff --->'+difference);
                                for(Inventory__c inventobj : lstofinventory)
                                {
                                    system.debug('diff inside for --->'+difference);
                                    if(inventobj.Id == listofcostprice[0].Product_From_Inventory__c)
                                    {
                                        system.debug('diff in innerif --->'+difference);
                                        system.debug('invent id --->'+inventobj.Id);
                                        system.debug('listof cp id --->'+listofcostprice[0].Product_From_Inventory__c);
                                        inventobj.Quantity__c -= difference;
                                        system.debug('Updated invent-->'+inventobj.Quantity__c);
                                    }
                                }
                            }
                            
                            if(newTotalQuantity < oldTotalQuantity) 
                            {
                                system.debug('inside else');
                                
                                //Calculate difference between new total quantity and old total quantity
                                difference =  oldTotalQuantity - newTotalQuantity;
                                for(Inventory__c inventobj : lstofinventory)
                                {
                                    system.debug('diff inside for --->'+difference);
                                    if(inventobj.Id == listofcostprice[0].Product_From_Inventory__c)
                                    {
                                        system.debug('diff in inner if --->'+difference);
                                        system.debug('invent id --->'+inventobj.Id);
                                        system.debug('listof cp id --->'+listofcostprice[0].Product_From_Inventory__c);
                                        inventobj.Quantity__c += difference;
                                        system.debug('Updated invent-->'+inventobj.Quantity__c);
                                    }
                                }
                            }
                        }
                    }
                    update lstofinventory;
                    
                }
                
                
                
                else
                {
                    System.debug('1--->Inside Primium Else');
                    
                    system.debug('new total quantity '+newTotalQuantity);
                    system.debug('old total quantity '+oldTotalQuantity);
                    for(Cost_Price__c obj : listofcostprice)
                    {
                        
                        if(listofcostprice[0].id ==  triggerold[0].id)
                        {
                            system.debug('3---->listofcostprice[0].id ==  triggerold[0].id');
                         
                            
                            if(newTotalQuantity != oldTotalQuantity)
                            {
                             
                              
                                for(Inventory__c inventobj : lstofinventory)
                                {
                                    
                                    
                                    if(inventobj.Id == listofcostprice[0].Product_From_Inventory__c)
                                    {
                                        
                                        inventobj.Quantity__c -= newTotalQuantity;  //changes
                                        
                                        system.debug('8---->Updated invent-->'+inventobj.Quantity__c);
                                    }
                                    if(inventobj.id == triggerold[0].Product_From_Inventory__c)
                                    {
                                        inventobj.Quantity__c += oldTotalQuantity;      
                                        
                                        system.debug('9---->Updated invent old-->'+inventobj.Quantity__c);
                                    }
                                    
                                }
                                
                            }
                            
                            else if(newTotalQuantity == oldTotalQuantity)
                            {
                                for(Inventory__c inventobj : lstofinventory)
                                {
                                    if(inventobj.Id == listofcostprice[0].Product_From_Inventory__c)
                                    {
                                        
                                        inventobj.Quantity__c -= newTotalQuantity;
                                        
                                        system.debug('10---->Updated invent-->'+inventobj.Quantity__c);
                                    }
                                    if(inventobj.Id == triggerold[0].Product_From_Inventory__c)
                                    {
                                        inventobj.Quantity__c += newTotalQuantity;     
                                        
                                        system.debug('11---->Updated invent old-->'+inventobj.Quantity__c);
                                    }
                                    
                                }
                               
                            }
                        }
                    }
                    update lstofinventory; 
                   
                }  
            }
        }
    }
}


Test Class:
@isTest 
public class TestCostPriceRevertQuantityTrigger 
{
    public static testmethod void runTest()
    {
        //create object of handler class..
       
       Id RecordTypeIdacc = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Logistic').getRecordTypeId();
        system.debug('Record type-->' +RecordTypeIdacc );
        Account objacc = new Account();
        
        objacc.Account_Company_Name__c = 'Chetna';
        objacc.Type_of_Logistic__c = 'Warehousing';
        objacc.Name = 'ABC';
        objacc.Worked_By__c	= 'Chetna';
        objacc.Type ='Bank';
        objacc.CurrencyIsoCode = 'EUR';
        objacc.Business_Entity__c = 'TRADEASIA INTERNATIONAL INDIA';
        objacc.RecordTypeId = RecordTypeIdacc;
        insert objacc ;
        
        //Create Product
        Product2 objpro = new Product2();
        objpro.Name = 'Sodium';
        objpro.CurrencyIsoCode = 'EUR'; 
        insert objpro;
        
        
        // Create Port
        Port__c pt = new Port__c();
        pt.Name = 'Chetna';
        insert pt;
        
        //Create Inventory1..
        Inventory__c inv1 = new Inventory__c();
        inv1.Account__c=objacc.id;
        inv1.Quantity__c=10;
        inv1.Product__c = objpro.id;
      	insert inv1;
        system.debug('inv1-->'+inv1);
        
        //Create Inventory2..
        	Inventory__c inv2 = new Inventory__c();
			inv2.Account__c=objacc.id;
			inv2.Quantity__c=10;
			inv2.Product__c = objpro.id;
			insert inv2;
			system.debug('inv2-->'+inv2);
        
        
        /*List<Inventory__c> lstinv1 = new List<Inventory__c>();
			lstinv1.add(inv1);
			List<Inventory__c> lstinv2 = new List<Inventory__c>();
			lstinv2.add(inv2);*/
        
        
        
        //Create Opportunity...
        Opportunity opp = new Opportunity ();
        opp.Name = 'Chetna';
        opp.AccountId = objacc.Id;
        opp.CurrencyIsoCode = 'INR';
        opp.ForecastCategoryName = 'Commit';
        opp.StageName = 'Proforma Invoice';
        opp.Sub_Stage__c = 'Issued';
        opp.CloseDate = date.today();
        opp.Worked_by__c = 'Chetna';
        opp.Product_Name__c = objpro.Id;
        opp.Origin__c = 'O11';
        opp.Description_of_Goods__c = 'Good';
        opp.Packaging_Details__c = 'P11';
        opp.Quantity__c = 10;
        opp.H_S_Code__c = 'H11';
        opp.Total_of_Containers__c = 5;
        opp.Container_Size__c = 'Trucking';
        opp.Port_of_Discharge__c = pt.Id;
        opp.Business_Entity__c = 'TRADEASIA INDIA';
        insert opp;
        
        //Create Cost Price...
         List<Cost_Price__c> lstcostold = new List<Cost_Price__c>();
        Cost_Price__c cp = new Cost_Price__c();
        cp.Opportunity__c = opp.Id;
        cp.Business_Entity__c ='TRADEASIA INDIA';
        cp.Sub_Entity_Tradeasia__c = objacc.id;
        cp.Status_Deal__c = '1st Nego';
        cp.STATUS__c = 'EXECUTED';
        cp.Product_From_Inventory__c = inv1.Id;
        cp.UOM__c = 'KGs';
        cp.Quantity__c = 22.6;
        cp.Quantity_Per_Container__c = 10;
        cp.Total_of_containers__c = 8;
        cp.Worked_By__c = 'Chetna';
        cp.Country_of_Final_Destination__c = 'India';
        lstcostold.add(cp);
        insert lstcostold;
        system.debug('lstcostold'+lstcostold);
        List<Cost_Price__c> lstcostnew = new List<Cost_Price__c>();
        cp.Quantity_Per_Container__c = 10;
        cp.Total_of_containers__c = 7;
        lstcostold.add(cp);
        //update lstcostold;
        //system.debug('lstcostnew'+lstcostnew);*/
       
        //new list
        //List<Cost_Price__c> lstcostnew = new List<Cost_Price__c>();
        
        //update cost price
        cp.Quantity_Per_Container__c = 10;
        cp.Total_of_containers__c = 9;
        cp.Product_From_Inventory__c = inv2.Id;
       // update cp;
        lstcostnew.add(cp);
        
       
        Test.startTest();
        
        RevertQuantityTriggerHandler obj = new RevertQuantityTriggerHandler();
     
        obj.onBeforeDelete(lstcostold);
        system.debug('lstcostnew'+lstcostnew);
        system.debug('lstcostold'+lstcostold);
        obj.onAfterUpdate(lstcostnew,lstcostold);
        
        Test.stopTest();
        
    }
}

 
Apex Trigger:
trigger CreateClientTenant on Lease_Summary__c (after update) {
    integer i = 1;
    List<Tenant__c> lstTenant = new List<Tenant__c>();
    List<Client__c> lstClient = new List<Client__c>();  
    for(Lease_Summary__c objLease : trigger.new){
        system.debug('objLease.Rent_start_date__c'+objLease.Rent_start_date__c);
        If(objLease.Rent_start_date__c == DATE.TODAY()){
            Tenant__c objtenant = new Tenant__c();
            objtenant.Rent_Start_Date__c = objLease.Rent_Start_Date__c;
            objtenant.Lease_Summary__c = objLease.id;
            lstTenant.add(objtenant);
            
        }
        system.debug('lstTenant'+lstTenant);
        insert lstTenant;
     }
}

 
public class contactPaginationController {
    //variable used in page.
    Public Integer size{get;set;}
    Public Integer noOfRecords{get; set;}
    public List<SelectOption> paginationSizeOptions{get;set;}
    public static final Integer QUERY_LIMIT = 10000;
    public static final Integer PAGE_SIZE = 5;
    
    public List <WrapperClass> wrapperRecordList{get;set;}
    Map<Id, WrapperClass> mapHoldingSelectedRecords{get;set;}
    
    //constructor calling init method.
    public contactPaginationController(){
        mapHoldingSelectedRecords = new Map<Id, WrapperClass>();
        init();
        
    }
    
    //Init method which queries the records from standard set controller.
    public void init() {
        wrapperRecordList = new List<WrapperClass>();
        for (Account cont : (List<Account>)setCon.getRecords()) {
            if(mapHoldingSelectedRecords != null && mapHoldingSelectedRecords.containsKey(cont.id)){
                wrapperRecordList.add(mapHoldingSelectedRecords.get(cont.id));
                
            }
            else{
                wrapperRecordList.add(new WrapperClass(cont, false));
            }
        }
    }
    
    /** Instantiate the StandardSetController from a query locater*/
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Id,Name, Phone FROM Account LIMIT : QUERY_LIMIT ]));
                
                // sets the number of records to show in each page view
                setCon.setPageSize(PAGE_SIZE);
            }
            return setCon;
        }
        set;
    }
    
    /** indicates whether there are more records after the current page set.*/
    public Boolean hasNext {
        get {
            return setCon.getHasNext();
        }
        set;
    }
    
    /** indicates whether there are more records before the current page set.*/
    public Boolean hasPrevious {
        get {
            return setCon.getHasPrevious();
        }
        set;
    }
    
    /** returns the page number of the current page set*/
    public Integer pageNumber {
        get {
            return setCon.getPageNumber();
        }
        set;
    }
    
    /** return total number of pages for page set*/
    Public Integer getTotalPages(){
        Decimal totalSize = setCon.getResultSize();
        Decimal pageSize = setCon.getPageSize();
        Decimal pages = totalSize/pageSize;
        return (Integer)pages.round(System.RoundingMode.CEILING);
    }
    
    /** returns the first page of the page set*/
    public void first() {
        updateSearchItemsMap();
        setCon.first();
        init();
    }
    
    /** returns the last page of the page set*/
    public void last() {
        updateSearchItemsMap();
        setCon.last();
        init();
    }
    
    /** returns the previous page of the page set*/
    public void previous() {
        updateSearchItemsMap();
        setCon.previous();
        init();
    }
    
    /** returns the next page of the page set*/
    public void next() {
        updateSearchItemsMap();
        setCon.next();
        init();
    }
    
    //This is the method which manages to remove the deselected records, and keep the records which are selected in map.
    private void updateSearchItemsMap() {
        for(WrapperClass wrp : wrapperRecordList){
            if(wrp.isSelected){
                mapHoldingSelectedRecords.put(wrp.contactRecord.id, wrp);
            }
            if(wrp.isSelected == false && mapHoldingSelectedRecords.containsKey(wrp.contactRecord.id)){
                mapHoldingSelectedRecords.remove(wrp.contactRecord.id);
            }
        }
    }
    
    //wrapper class being used for checkbox showing.
    public class WrapperClass {
        public Boolean isSelected {get;set;}
        public Account contactRecord {get;set;}
        public WrapperClass(Account contactRecord, Boolean isSelected) {
            this.contactRecord = contactRecord;
            this.isSelected = isSelected;
        }
    }
}
 
<apex:page controller="contactPaginationController" docType="html-5.0" tabStyle="Account">
   <apex:sectionHeader title="Contact" subtitle="Contact Pagination" />
    <apex:form id="theForm">
      <apex:pageBlock title="All Contacts" rendered="{!wrapperRecordList.size!=0}" id="pbId" >
        <apex:pageBlockTable value="{!wrapperRecordList}" var="cont">
           <apex:column headerValue="Select">
             <apex:inputCheckbox value="{!cont.isSelected}"/>
           </apex:column>
           <apex:column headerValue="Name">
             <apex:outputField value="{!cont.contactRecord.name}"/>
           </apex:column>
           
           <apex:column headerValue="Phone">
            <apex:outputField value="{!cont.contactRecord.Phone}"/>
           </apex:column>
       </apex:pageBlockTable>
          
          <apex:repeat value="{!mapHoldingSelectedRecords}" var="maper">
           <apex:outputText value="{!cont}" />
        <apex:outputText value="{!mapHoldingSelectedRecords[maper]}" />
       </apex:repeat>
 
 <!-- Action Buttons visible on bottom of page for pagination -->
       <apex:outputPanel style="text-align:center;" layout="block">
          <apex:commandButton value="First" reRender="pbId" action="{!first}" disabled="{!NOT(hasPrevious)}" status="paginationStatus"/>
          <apex:commandButton value="Previous" rerender="pbId" action="{!previous}" disabled="{!NOT(hasPrevious)}" status="paginationStatus"/>&nbsp;Page {!pageNumber} of {!totalPages}&nbsp;
          <apex:commandButton value="Next" rerender="pbId" action="{!next}" disabled="{!NOT(hasNext)}" status="paginationStatus"/>
          <apex:commandButton value="Last" rerender="pbId" action="{!last}" disabled="{!NOT(hasNext)}" status="paginationStatus"/>
          <apex:actionStatus id="paginationStatus">
             <apex:facet name="start">
                 Please wait...<img src="/img/loading32.gif" style="width: 18px;"/>
             </apex:facet>
          </apex:actionStatus>
       </apex:outputPanel>
 </apex:pageBlock>
 </apex:form>
</apex:page>
Can Any One Help..

 
Visualforce Page
<apex:page controller="thousandLimit">
    <apex:form>
        <apex:pageBlock >
            <apex:repeat value="{!thousandBlocks}" var="block">
                
            <apex:pageBlockTable value="{!block}" var="c">
               
            <apex:column value="{!c.cases.name}"/>
                            
            </apex:pageBlockTable>
        </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page>

controller
public class thousandLimit {
 private List<limitWrapper> thousandBlocks = new List<limitWrapper>();
   
    private final integer listLimit;
   
    public thousandLimit()
    {
        listLimit = 1000;
    }
   
    public List<limitWrapper> getthousandBlocks()
    {
        thousandBlocks = new limitWrapper[]{};
       
        integer counter = 0;
        integer loopCount = 0;
        boolean Selected =true;
        List<Account> tmpcase = new List<Account>();
       
        for(Account c:[select id,name from Account])
        {
            if(counter < listLimit)
            {
                tmpcase.add(c);
                counter++;
            }
            else
            {
                loopCount++;
                thousandBlocks.add(new limitWrapper(tmpcase,Selected));
                tmpcase = new List<Account>();
                tmpcase.add(c);
                counter = 0;
            }           
        }
       
        if(thousandBlocks.size() == 0)
        {
            loopCount++;
            thousandBlocks.add(new limitWrapper(tmpcase,Selected));
        }
       
        return thousandBlocks;
    }
   
    public class limitWrapper
    {
        public List<Account> cases {get;set;}
         public boolean Selected {get;set;}
        //public integer blockNumber {get;set;}
        public limitWrapper(List<Account> accs, boolean i)
        {
            cases = accs;
            Selected = i;
        }
       
    }
}
Collection size 2,043 exceeds maximum size of 1,000  Error Face Any Solution
VisualForce Page :-

<apex:page standardController="Account"  tabstyle="account" sidebar="false" extensions="mergeAccount">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/datatables.min.js"> </script>
     <style> 
          
       
         .dataTables_wrapper .dataTables_paginate .paginate_button.current, .dataTables_wrapper .dataTables_paginate .paginate_button.current:hover {
        color: white!important;
        border: 1px solid #cacaca;
        background-color: white;
        background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, white), color-stop(100%, gainsboro));
        background: -webkit-linear-gradient(top, white 0%, gainsboro 100%);
        background: -moz-linear-gradient(top, white 0%, gainsboro 100%);
        background: -ms-linear-gradient(top, white 0%, gainsboro 100%);
        background: -o-linear-gradient(top, white 0%, gainsboro 100%);
        border-radius: 7px;
        background: dodgerblue;
        }
        <!-- List View (DataTable CSS)-->
        
        .dataTable>tbody>tr:nth-child(even)>td, 
        .dataTable>tbody>tr:nth-child(even)>th {
        background-color: #e8e8e8 !important; 
        }
        
        .dataTable>tbody>tr:nth-child(odd)>td, 
        .dataTable>tbody>tr:nth-child(odd)>th {
        background-color: #d2deea!important; 
        }
        
        .header_styling{
        font-family:Raleway:200;
        background-color: #e1e1e1 !important ; 
        }
        
        .dataTables_length, .dataTables_filter, .dataTables_info, .dataTables_paginate {        
        padding: 3px;        
        }       

        
        
    </style>
 <apex:form id="dForm">
  <apex:pageBlock >
      
      <apex:pageBlockTable value="{!wrapAccountList}" var="a" id="d" styleclass="example" rendered="{!bolvar1}">
        <apex:column >
                        <apex:inputCheckbox value="{!a.selected}" >
                            <!-- <apex:actionSupport action="{!processSelected}"  event="onchange" />-->
                        </apex:inputCheckbox>
                    </apex:column>
        <apex:column value="{!a.acc.name}"/>
        <apex:column value="{!a.acc.type}" />
        <apex:column value="{!a.acc.phone}"/>
            </apex:pageBlockTable>
         <apex:commandButton value="Account Merge" action="{!nextButton}" reRender="dForm" rendered="{!bolvar1}"/>
        <br/>
             <apex:pageblock id="table" rendered="{!bolvar2}">
         choose master account&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    
            <apex:selectList value="{!SelectAccount}" size="1">                                 
                <apex:selectOptions value="{!lstSelectOption}"/>
                 
            </apex:selectList>
                <apex:commandbutton value="Get Selected" action="{!Selectedmaster}"  /> <br/>
                    
                </apex:pageblock>
         
                        
             
        </apex:pageBlock>   
                 
  </apex:form>
  <script>
    $('table.example').DataTable({
       
        "pagingType": "full_numbers"

        });
    </script>
</apex:page>


Controller :-

public class mergeAccount {
    
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<wrapAccount> selectedAccounts{get;set;}
    public Boolean bolvar {get; set;}
    public Boolean bolvar1{get;set;}
    public Boolean bolvar2{get;set;} 
    public Boolean bolvar3{get;set;} 
    public String SelectAccount{get;set;}
    public Account objMasterAccount {get;set;}
    public List<SelectOption> lstSelectOption {get;set;}
    public String AccountId;
    public Account objAccount;
    public string AccountName ;
    public ID AccountID1;
    public List<Account> lstAccount = new List<Account>();
    public List<Account> lstAccount1 = new List<Account>();
    public mergeAccount(ApexPages.StandardController controller) {
        
        system.debug('lstAccount'+lstAccount);
        bolvar1 = true;
        bolvar2 = false;
        //objAccount= (Account)Controller.getRecord().id;
        system.debug('objAccount'+objAccount);
        
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();
            String query='select id';
            for(String s : objectFields.keySet()) {
                if(s != 'Id'){
                    SObjectField test=objectFields.get(s); 
                    //system.debug('test' +test);
                    //if(test.getDescribe().isUpdateable()){ 
                    query += ', ' + s + ' ';
                }
                //}
            }
            
            query +=' FROM Account';
            System.debug(query);
            List<Account> lstAccount = new List<Account>();
            lstAccount = database.query(query);
            //System.debug(lstAccount);
            for(Account a: lstAccount) {
                wrapAccountList.add(new wrapAccount(a,bolvar));
                
                
            }
        }
    }
    
    public void getAccountNames() {
       lstSelectOption= new List<SelectOption>();
        lstSelectOption.add( new SelectOption('','--Select--'));
        for( wrapAccount wrapacc :  selectedAccounts) {
            lstSelectOption.add( new SelectOption(wrapacc.acc.Id,wrapacc.acc.name));
           system.debug('accOptions'+lstSelectOption);
        }   
    }
    
    public void nextButton(){
        selectedAccounts = new List<wrapAccount>();
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(new wrapAccount(wrapAccountObj.acc,wrapAccountObj.selected));  
            }
        }
        getAccountNames();
        bolvar1 = false;
        bolvar2 = true;
        
    }
    
    public PageReference  Selectedmaster(){
        objMasterAccount = new Account();
        objAccount = new Account();
        SobjectField[] fields =  Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().values();
        System.debug(fields);
        for(wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id == SelectAccount) 
                objMasterAccount = wrapacc.acc;
            //AccountID1 = wrapacc.accId;
            system.debug('objMasterAccount'+objMasterAccount);
        }
        
        for( wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id != SelectAccount){
                for(SObjectField field:fields){  
                    if(field.getDescribe().isUpdateable()){   
                        system.debug('masterLead.get(field)'+objMasterAccount.get(field));
                        if(objMasterAccount.get(field)==null && wrapacc.acc.get(field)!=null ){     
                            objMasterAccount.put(field,wrapacc.acc.get(field));
                        }
                    }
                }
            }
        }
        update objMasterAccount;
        bolvar3 = false; 
        PageReference pageRef = new PageReference('/apex/PopUp');
        pageRef.setRedirect(true);
        return pageRef;
    }
    
    public PageReference ok(){
        PageReference pageRef = new PageReference('/001/o');
        pageRef.setRedirect(true);
        return pageRef; 
    }
    
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        //public id accId {get;set;}
        public wrapAccount(Account a,Boolean bolvar) {
            acc = a;
            selected = bolvar;
            //accId = aId;
        }
    } 
}
Apex Class:

public class mergeAccount {
    
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<wrapAccount> selectedAccounts{get;set;}
    public Boolean bolvar {get; set;}
    public Boolean bolvar1{get;set;}
    public Boolean bolvar2{get;set;} 
    public Boolean bolvar3{get;set;} 
    public String SelectAccount{get;set;}
    public Account objMasterAccount {get;set;}
    public List<SelectOption> lstSelectOption {get;set;}
    public String AccountId;
    public Account objAccount;
    public string AccountName ;
    public ID AccountID1;
    public List<Account> lstAccount = new List<Account>();
    public List<Account> lstAccount1 = new List<Account>();
    public mergeAccount(ApexPages.StandardController controller) {
        
        system.debug('lstAccount'+lstAccount);
        bolvar1 = true;
        bolvar2 = false;
        //objAccount= (Account)Controller.getRecord().id;
        system.debug('objAccount'+objAccount);
        
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();
            String query='select id';
            for(String s : objectFields.keySet()) {
                if(s != 'Id'){
                    SObjectField test=objectFields.get(s); 
                    //system.debug('test' +test);
                    //if(test.getDescribe().isUpdateable()){ 
                    query += ', ' + s + ' ';
                }
                //}
            }
            
            query +=' FROM Account';
            System.debug(query);
            List<Account> lstAccount = new List<Account>();
            lstAccount = database.query(query);
            //System.debug(lstAccount);
            for(Account a: lstAccount) {
                wrapAccountList.add(new wrapAccount(a,bolvar));
                
                
            }
        }
    }
    
    public void getAccountNames() {
        system.debug('AccountId'+AccountId);
        /*AccountId=Apexpages.currentpage().getParameters().get('id');
        lstAccount1 =[Select id,name from Account where id =:AccountId];
        if(lstAccount1.size()>0)
        {
            AccountName =  lstAccount1[0].Name;
            AccountID1 = lstAccount1[0].id;
            system.debug('AccountName'+AccountName);
        }*/
        
        system.debug('AccountId'+AccountId);
        // selectedAccounts = new List<wrapAccount>();
        lstSelectOption= new List<SelectOption>();
        lstSelectOption.add( new SelectOption('','--Select--'));
        for( wrapAccount wrapacc :  selectedAccounts) {
            lstSelectOption.add( new SelectOption(wrapacc.acc.Id,wrapacc.acc.name));
            
            //lstSelectOption.add(new SelectOption(AccountID1,AccountName));
            system.debug('accOptions'+lstSelectOption);
        }
        
    }
    
    public void nextButton(){
        selectedAccounts = new List<wrapAccount>();
        
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(new wrapAccount(wrapAccountObj.acc,wrapAccountObj.selected));
                
            }
        }
        getAccountNames();
        bolvar1 = false;
        bolvar2 = true;
        
    }
    
    public PageReference  Selectedmaster(){
        objMasterAccount = new Account();
        objAccount = new Account();
        SobjectField[] fields =  Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().values();
        System.debug(fields);
        for(wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id == SelectAccount)
                objMasterAccount = wrapacc.acc;
            //AccountID1 = wrapacc.accId;
            system.debug('objMasterAccount'+objMasterAccount);
        }
        for( wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id != SelectAccount){
                for(SObjectField field:fields){  
                    if(field.getDescribe().isUpdateable()){   
                        system.debug('masterLead.get(field)'+objMasterAccount.get(field));
                        if(objMasterAccount.get(field)==null && wrapacc.acc.get(field)!=null ){     
                            objMasterAccount.put(field,wrapacc.acc.get(field));
                        }
                    }
                }
            }
        }
        update objMasterAccount;
        bolvar3 = false; 
        PageReference pageRef = new PageReference('/apex/PopUp');
        pageRef.setRedirect(true);
        return pageRef;
    }
    
    public PageReference ok(){
        PageReference pageRef = new PageReference('/001/o');
        pageRef.setRedirect(true);
        return pageRef; 
    }
    
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        //public id accId {get;set;}
        public wrapAccount(Account a,Boolean bolvar) {
            acc = a;
            selected = bolvar;
            //accId = aId;
        }
    } 
}



Test Class
@isTest
public class mergeAccountTest {
    
    public static testmethod void AccountMergeTest(){
        Map<string, schema.RecordTypeInfo> rtMap = Schema.SObjectType.Account.getRecordTypeInfosByName();
        Id VV=rtMap.get('VV').getRecordTypeId();
        Id MVS=rtMap.get('MVS - Remind A Pet').getRecordTypeId();
        Id VVR=rtMap.get('VVR').getRecordTypeId();
        Id VVANDVVR=rtMap.get('VV and VVR').getRecordTypeId();
        
        
        Account objAccount = new Account();
        objaccount.Name = 'Test';
        objaccount.RecordTypeId =VV;
        insert objAccount;
        
        PageReference pageRef = Page.PopUp;
        Test.setCurrentPage(pageRef);
        
        
        ApexPages.StandardController sc = new ApexPages.standardController(objAccount);
        mergeAccount controller = new mergeAccount(sc);
        Account objacc = new Account();
        Boolean selected = true; 
        controller.bolvar3 = true;
        controller.SelectAccount ='26551025862uiyty';
        
        mergeAccount.wrapAccount wrrap = new mergeAccount.wrapAccount(objacc,selected);
        
        
        controller.nextButton();
        controller.getAccountNames();
         PageReference objPageRef1 = controller.ok();
          for(mergeAccount.wrapAccount wrp : controller.selectedAccounts )
            {
                wrp.selected = true;
            }            
 
        PageReference objPageRef = controller.Selectedmaster();
       
    }
    
}
public class mergeAccount {
    
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<wrapAccount> selectedAccounts{get;set;}
    public Boolean bolvar {get; set;}
    public Boolean bolvar1{get;set;}
    public Boolean bolvar2{get;set;} 
    public Boolean bolvar3{get;set;} 
    public String SelectAccount{get;set;}
    public Account objMasterAccount {get;set;}
    public List<SelectOption> lstSelectOption {get;set;}
    public String AccountId;
    public Account objAccount;
    public string AccountName ;
    public ID AccountID1;
    public List<Account> lstAccount = new List<Account>();
    public List<Account> lstAccount1 = new List<Account>();
    public mergeAccount(ApexPages.StandardController controller) {
    
        system.debug('lstAccount'+lstAccount);
        bolvar1 = true;
        bolvar2 = false;
        //objAccount= (Account)Controller.getRecord().id;
        system.debug('objAccount'+objAccount);
        
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();
            String query='select id';
            for(String s : objectFields.keySet()) {
                if(s != 'Id'){
                SObjectField test=objectFields.get(s); 
                //system.debug('test' +test);
                //if(test.getDescribe().isUpdateable()){ 
                query += ', ' + s + ' ';
                }
                //}
            }
            
            query +=' FROM Account';
            System.debug(query);
            List<Account> lstAccount = new List<Account>();
            lstAccount = database.query(query);
            //System.debug(lstAccount);
            for(Account a: lstAccount) {
                wrapAccountList.add(new wrapAccount(a,bolvar,AccountID1));
                
                
            }
        }
    }
     
    public void getAccountNames() {
        system.debug('AccountId'+AccountId);
        AccountId=Apexpages.currentpage().getParameters().get('id');
        lstAccount1 =[Select id,name from Account where id =:AccountId];
        if(lstAccount1.size()>0)
        {
            AccountName =  lstAccount1[0].Name;
            AccountID1 = lstAccount1[0].id;
            system.debug('AccountName'+AccountName);
        }
       
        system.debug('AccountId'+AccountId);
        // selectedAccounts = new List<wrapAccount>();
        lstSelectOption= new List<SelectOption>();
        lstSelectOption.add( new SelectOption('','--Select--'));
        for( wrapAccount wrapacc :  selectedAccounts) {
            lstSelectOption.add( new SelectOption(wrapacc.acc.Id,wrapacc.acc.name));
            lstSelectOption.add(new SelectOption(AccountID1,AccountName));
            system.debug('accOptions'+lstSelectOption);
        }
        
    }
    
    public void nextButton(){
        selectedAccounts = new List<wrapAccount>();
        AccountId=Apexpages.currentpage().getParameters().get('id');
        lstAccount1 =[Select id,name from Account where id =:AccountId];
        if(lstAccount1.size()>0)
        {
            AccountName =  lstAccount1[0].Name;
            AccountID1 = lstAccount1[0].id;
            system.debug('AccountName'+AccountID1);
        }
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(new wrapAccount(wrapAccountObj.acc,wrapAccountObj.selected,wrapAccountObj.accId));
                
            }
        }
        getAccountNames();
        bolvar1 = false;
        bolvar2 = true;
        
    }
    
    public void  Selectedmaster(){
        System.debug(SelectAccount);
        

        //selectedAccounts = new List<wrapAccount>();
        objMasterAccount = new Account();
        objAccount = new Account();
        SobjectField[] fields =  Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().values();
        System.debug(fields);
        for(wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id == SelectAccount)
                objMasterAccount = wrapacc.acc;
                AccountID1 = wrapacc.accId;
            system.debug('objMasterAccount'+objMasterAccount);
        }
        
        for( wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id != SelectAccount){
                for(SObjectField field:fields){  
                    if(field.getDescribe().isUpdateable()){   
                        system.debug('masterLead.get(field)'+objMasterAccount.get(field));
                        if(objMasterAccount.get(field)==null && wrapacc.acc.get(field)!=null ){     
                            objMasterAccount.put(field,wrapacc.acc.get(field));
                            objMasterAccount.put(field,wrapacc.accId);
                            system.debug('objMasterAccount'+objMasterAccount);
                            //masterLead.put(field,'Amit Shah');
                            system.debug('objMasterAccount'+objMasterAccount.get(field));
                        }
                    }
                }
            }
        }
        update objMasterAccount;
        bolvar3 = false; 

    }
    
    public PageReference ok(){
       PageReference pageRef = new PageReference('/001/o');
         pageRef.setRedirect(true);
         return pageRef; 
    }
    
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        public id accId {get;set;}
        public wrapAccount(Account a,Boolean bolvar, id aId) {
            acc = a;
            selected = bolvar;
            accId = aId;
        }
    } 
}
@isTest
public class OpportunityAmountInWordsTest
{
  
    Public static testmethod void OpportunityAmountInWordsTM()
    {
        RecordType rt = [select id,Name from RecordType where SobjectType='Account' and Name='Supplier' Limit 1];
        Account Acc =New Account();
            Acc.RecordTypeId=rt.id;
            Acc.Name='Test';
            Acc.GST_Reg_No__c='test1';
            Acc.TAX_IDENTIFICATION_NUMBER_VAT__c='Test11';
            Acc.IMPORT_EXPORT_CODE_IEC__c='test12';
            Insert Acc;
       
       Product2 Pro =New Product2 ();
            Pro.Name ='tEST';
            Pro.CurrencyIsoCode='USD';
            Insert Pro;
       Order odd =New Order();
            odd.AccountId=acc.id;
            odd.EffectiveDate=System.today();
            odd.Status__c='Draft';
            odd.Product_Name__c=pro.id;
            odd.Quantity__c=1234;
            odd.Quantity_per_Container__c=23;
            odd.Quantity_per_Packaging_Material__c =55;
            odd.Status='Draft';
            Insert odd;
            
        Opportunity opp =New Opportunity();
            opp.Name='Test';
            opp.accountId = Acc.id;
            opp.CloseDate=system.today();
            opp.CurrencyIsoCode ='USD';
            opp.Worked_by__c='Neha';
            opp.Product_Name__c=pro.id;
            opp.Description_of_Goods__c='test';
            opp.Origin__c='test';
            opp.Packaging_Details__c='trueuus';
            opp.Quantity__c=10000;
            opp.H_S_Code__c='amit';
            opp.Container_Size__c='20 FCL';
            // opp.Agent_Name__c=Customer.id;
            opp.StageName='Enquiry';
            // opp.Agent_Fee_IO__c=123;
            Insert opp;
            
            List<Cost_Price__c> lCostPr = new List<Cost_Price__c>();
            Cost_Price__c Cost1 =New Cost_Price__c();
            Cost1.Opportunity__c=opp.id;
            Cost1.Supplier_Name__c=Acc.id;
            //Cost1.Opportunity__c=opp.Accountid;
            Cost1.Country_of_Final_Destination_Picklist__c='India';
            Cost1.CurrencyIsoCode='USD';
            Cost1.UOM__c='Tonnes';
            cost1.Payment_Status__c = 'DUE';
            cost1.Payment_Receivable_Date__c = System.now().date().addDays(-40);
               
           lCostPr.add(cost1);
            Insert lCostPr;          
           
}
    
}
I have created a 6 objects 
Test1
Test2
Test3
Test4
Test5
Test6

Test6(Lookup with Test5)
Test5(Lookup with Test4)
Test4(Lookup with Test3)
Test3(Lookup with Test2)
Test2(Lookup with Test1)

i want Test1 records in test 6 using soql

Please Help

Thanks,

Regards
Amit Jadhav
My requirement is Display Avg IN Visualforce page 
Field Is a Quantity__c so Show the Average Of Quantity 
for example 
Price__c * Qyt__c = Total_Price__c (Total price is formula field)
Total_Price__c * Disscount_per__c = Disscount__c (Disscount Is also formula field)
Disscount__c + Total_Price__c = Amount (Amount is  also formula field)


how to cover this filed in test class
Controller:

public with sharing class costsheet {
   
    

    public String OrderId;
    public Order ord;
    
    
    public costsheet(ApexPages.StandardController controller) {
      listIex =0.0;
      CFSList =0.0;
      CHAList =0.0;
      CHAListS =0.0;
      ord= (Order)Controller.getRecord();
      OrderId=Apexpages.currentpage().getParameters().get('id');
      system.debug('listStemer>>'+OrderId);
      listStemer=[Select Id,subtotal__c,Supplier_Order__c from Shipper_Info_India__c where Supplier_Order__c =:ord.id AND RecordType.Name='Steamer Charges' limit 1]  ;
      system.debug('listStemer>>'+listStemer);
     if(listStemer.size()>0)
     {
     listIex =listStemer[0].subtotal__c;
     system.debug('listStemer>>'+listIex );
     }
     listCHAChargesR=[Select Id,subtotal__c,Supplier_Order__c  from Shipper_Info_India__c where Supplier_Order__r.id =:ord.id AND RecordType.Name='CHA Charges' AND Bill_Type__c = 'Reimbursement Type'] ;
     if(listCHAChargesR.size()>0)
     {
     CHAList =listCHAChargesR[0].subtotal__c;
     }
     listCHAChargesS=[Select Id,subtotal__c,Supplier_Order__c  from Shipper_Info_India__c where Supplier_Order__r.id =:ord.id AND RecordType.Name='CHA Charges' AND Bill_Type__c = 'Service Type'] ;
     if(listCHAChargesS.size()>0)
     {
     CHAListS =listCHAChargesS[0].subtotal__c;
     }
     listCFSCharges=[Select Id,subtotal__c,Supplier_Order__c  from Shipper_Info_India__c where Supplier_Order__r.id =:ord.id AND RecordType.Name='CFS Charges' limit 1] ;
     if(listCFSCharges.size()>0)
     {
     CFSList =(listCFSCharges[0].subtotal__c).setScale(2);
     }
     
     Calculation();
    
    
    }
    
        public List<Shipper_Info_India__c > listStemer;
        public List<Shipper_Info_India__c > listCFSCharges;
        public List<Shipper_Info_India__c > listCHAChargesR;
        public List<Shipper_Info_India__c > listCHAChargesS;
        public Decimal CFSList {get;set;}
        public Decimal CHAList {get;set;}
        Public Decimal listIex {get;set;}
        public Decimal CHAListS {get;set;}
        public List<Order> ordList = new List<Order>();
        public Decimal TotalAmount_3{get;set;}
        public Decimal TotalFreightAmount_19{get;set;}
        public Decimal TotalFreightAmount_21{get;set;}
        public Decimal TotalFreightAmount_c21{get;set;}
        public Decimal TotalFreightAmount_d21{get;set;}
        public Decimal BasicDuty_c23{get;set;}
        public Decimal BasicDuty_d23{get;set;}
        public Decimal Cess_c24{get;set;}
        public Decimal Cess_d24{get;set;}
        public Decimal TotalCustomDuty_g25{get;set;}
        public Decimal TotalCustomDuty_c25{get;set;}
        public Decimal TotalCustomDuty_d25{get;set;}
        public Decimal ShippingLine_c27 {get;set;}
        public Decimal ShippingLine_d27 {get;set;}
        public Decimal StorageCFS_c32 {get;set;}
        public Decimal StorageCFS_d32 {get;set;}
        public Decimal Others_c30 {get;set;} 
        public Decimal Others_d30 {get;set;} 
        public Decimal Clearing_c31 {get;set;}
        public Decimal Clearing_d31 {get;set;}
        public Decimal TotalC {get;set;}
        public Decimal TotalCost{get;set;}
        public decimal TotalC_c37 {get;set;}
        public decimal TotalC_d37 {get;set;}
        public decimal TotalCost_c38 {get;set;}
        public decimal TotalCost_d38 {get;set;}
        
            
        public void Calculation(){
         TotalAmount_3 = 0;
         TotalFreightAmount_19= 0;
         if(ord.Quantity__c != NULL && ord.Unit_Price__c != null){
            TotalAmount_3 = (ord.Unit_Price__c *ord.Quantity__c).setScale(2);
          }else{
           TotalAmount_3=0;
          }
          if(ord.Total_Insurance__c != null){
          // Need to update this with adding Freight charges
           TotalFreightAmount_19= (ord.Total_Insurance__c+ord.Total_Sea_Freight_Charges__c+TotalAmount_3).setscale(2) ;
           }else{
           TotalFreightAmount_19=0;
           }
           if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalFreightAmount_21 = (TotalFreightAmount_19*ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
            TotalFreightAmount_21=(0+TotalFreightAmount_19).setscale(2);
          }
          if(TotalFreightAmount_19 != 0)
           {
           TotalFreightAmount_c21 = (TotalFreightAmount_21/ord.Quantity__c/1000).setscale(2);
          }
           
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalFreightAmount_d21 = (TotalFreightAmount_c21*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
          TotalFreightAmount_d21=0;
          }
          if(ord.Basic_Customs_Duty_value__c != null)
           {
           BasicDuty_c23 = (ord.Basic_Customs_Duty_value__c/ord.Quantity__c/1000).setscale(2);
          }else{
           BasicDuty_c23=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           BasicDuty_d23 = (BasicDuty_c23*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
           BasicDuty_d23=0;
          }  
          if(ord.Social_Welfare_Surcharge__c != null)
           {
           Cess_c24 = (ord.Social_Welfare_Surcharge__c/ord.Quantity__c/1000).setscale(2);
          }else{
           Cess_c24=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           Cess_d24 = (Cess_c24*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
           Cess_d24=0;
          }  
          if(ord.Basic_Customs_Duty_value__c != null && ord.Social_Welfare_Surcharge__c != null)
          {
           TotalCustomDuty_g25=(ord.Basic_Customs_Duty_value__c+ord.Social_Welfare_Surcharge__c).setscale(2);
          }else{
            TotalCustomDuty_g25=0;
          }
          if(TotalCustomDuty_g25 != 0)
           {
           TotalCustomDuty_c25 = (TotalCustomDuty_g25/ord.Quantity__c/1000).setscale(2);
          }else{
           TotalCustomDuty_c25 =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalCustomDuty_d25 = (TotalCustomDuty_c25*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           TotalCustomDuty_d25 =0;
          }
          if(listIex != null)
           {
           ShippingLine_c27 = (listIex/ord.Quantity__c/1000).setscale(2);
          }else{
           ShippingLine_c27 =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           ShippingLine_d27 = (ShippingLine_c27*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           ShippingLine_d27 =0;
          }
          if(CFSList != null)
           {
           StorageCFS_c32 = (CFSList/ord.Quantity__c/1000).setscale(2);
          }else{
           StorageCFS_c32 =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           StorageCFS_d32 = (StorageCFS_c32*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           StorageCFS_d32 =0;
          }
          
          if(CHAList != null)
           {
           Others_c30 = (CHAList/ord.Quantity__c/1000).setscale(2);
          }else{
           Others_c30  =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           Others_d30  = (Others_c30 *1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           Others_d30  =0;
          }
          
          if(CHALists != null)
           {
           Clearing_c31 = (CHALists/ord.Quantity__c/1000).setscale(2);
          }else{
           Clearing_c31  =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           Clearing_d31  = (Clearing_c31 *1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           Clearing_c31  =0;
          }
          
          
          TotalC = (listIex+CHAList+CHAListS+CFSList).setscale(2);
          TotalCost = (TotalC+TotalFreightAmount_21+TotalCustomDuty_g25).setscale(2);
          
          if(TotalC != null)
           {
           TotalC_c37= (TotalC/ord.Quantity__c/1000).setscale(2);
          }else{
           TotalC_c37=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalC_d37= (TotalC_c37*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           TotalC_d37=0;
          }
          
           if(TotalCost != null)
           {
           TotalCost_c38= (TotalCost/ord.Quantity__c/1000).setscale(2);
          }else{
           TotalCost_c38=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalCost_d38= (TotalCost_c38*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           TotalCost_d38=0;
          }
          
          
        }
          
       
        
           
      
   //Method to Save Attachments   
    
    public PageReference  SaveAttachmentpdf() {
        system.debug('In save');
        blob pdfBody;
        PageReference thePDF =  new PageReference('/apex/costsheetpdf?id='+OrderId);
        system.debug('ORD--'+OrderId);
        thePDF.setRedirect(true);
           
          if(Test.isRunningTest()) { 
             pdfBody = blob.valueOf('Unit.Test');
            } else {
             pdfBody = thePDF.getContentAsPDF();
           }
            Attachment attach = new Attachment();
            attach.body = pdfBody;
            attach.Name='CostSheetPdf '+System.Now();
            system.debug('OrderId'+OrderId);
            attach.ParentId=OrderId;
            attach.ContentType = 'application/pdf';
            Insert attach;
            
        if (attach == null){
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Error will Saving a file .Please check the content of the file'));  
           }
        if (attach != null){
             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Quote Pdf generated successfully'));
            
          }
      PageReference qtpage = new PageReference('/'+OrderId);
      qtpage.setRedirect(true); 
      
      return thePDF;
   }
This is my class
public with sharing class costsheet {

    

 
 public List<Order> ordwrap {get;set;}
 public List<Opportunity> oppwrap {get;set;}
  public List<SOWrapper> wrapper {get;set;}
 
 
 
 public costsheet()
 {
  ordwrap=[Select id from Order limit 5];
  oppwrap=[select Id,name,Account.Name from opportunity limit 5];
  wrapper = new List<SOWrapper>() ;
        for(Integer i=0 ; i < 5 ; i++)
            wrapper.add(new SOWrapper(ordwrap[i] , oppwrap[i])) ;
  
 }

  
        public class SOWrapper{
        public Order order{get;set;}
        public Opportunity opportunity{get;set;}
        //public Cost_Price__c costprice{get;set;}
        
        public SOWrapper(Order ord, Opportunity opp){
            order= ord;
            opportunity = opp;
            //costprice = cp;
        }
    }
    
}
This is Apex Class
public with sharing class costsheet {
 
 public costsheet(ApexPages.StandardController controller) {

    }

 public List<Order> ordwrap = new List<Order>();
 public List<Opportunity> oppwrap = new List<Opportunity>();
 
 
 
 public costsheet()
 {
  this.SOWrappers = new List<SOWrapper>();
  ordwrap=[Select id,Cost_Price_As_per_Allocation__r.CI__c from Order];
  oppwrap=[select Id,name,Account.Name from opportunity];
  for(opportunity opp:oppwrap){
                for(Order ord: ordwrap){
                    If(opp.id == ord.id)
                    {
                        SOWrapper wrapper = new SOWrapper(opp, ord);
                        this.SOWrappers.add(wrapper);
                    }
                        
                    }
                }
 }
 public List<SOWrapper> SOWrappers{get;set;}
 public class SOWrapper{
        public Order order{get;set;}
        public Opportunity opportunity{get;set;}
        public Cost_Price__c costprice{get;set;}
        
        public SOWrapper(Order ord, Opportunity opp,Cost_Price__c cp){
            order= ord;
            opportunity = opp;
            costprice = cp;
        }
    }
    
}
<apex:page controller="costsheet">
<apex:form >
  <apex:pageblock >
   <apex:pageblockSection >
   <table>
   <tr>
    <td><apex:inputField value="{!Ord.Status}"/></td>
    
    </tr>
   </table>
   </apex:pageblockSection>
  </apex:pageblock>
  </apex:form>
</apex:page>
 
Apex Trigger:
trigger CreateClientTenant on Lease_Summary__c (after update) {
    integer i = 1;
    List<Tenant__c> lstTenant = new List<Tenant__c>();
    List<Client__c> lstClient = new List<Client__c>();  
    for(Lease_Summary__c objLease : trigger.new){
        system.debug('objLease.Rent_start_date__c'+objLease.Rent_start_date__c);
        If(objLease.Rent_start_date__c == DATE.TODAY()){
            Tenant__c objtenant = new Tenant__c();
            objtenant.Rent_Start_Date__c = objLease.Rent_Start_Date__c;
            objtenant.Lease_Summary__c = objLease.id;
            lstTenant.add(objtenant);
            
        }
        system.debug('lstTenant'+lstTenant);
        insert lstTenant;
     }
}

 
Visualforce Page
<apex:page controller="thousandLimit">
    <apex:form>
        <apex:pageBlock >
            <apex:repeat value="{!thousandBlocks}" var="block">
                
            <apex:pageBlockTable value="{!block}" var="c">
               
            <apex:column value="{!c.cases.name}"/>
                            
            </apex:pageBlockTable>
        </apex:repeat>
        </apex:pageBlock>
    </apex:form>
</apex:page>

controller
public class thousandLimit {
 private List<limitWrapper> thousandBlocks = new List<limitWrapper>();
   
    private final integer listLimit;
   
    public thousandLimit()
    {
        listLimit = 1000;
    }
   
    public List<limitWrapper> getthousandBlocks()
    {
        thousandBlocks = new limitWrapper[]{};
       
        integer counter = 0;
        integer loopCount = 0;
        boolean Selected =true;
        List<Account> tmpcase = new List<Account>();
       
        for(Account c:[select id,name from Account])
        {
            if(counter < listLimit)
            {
                tmpcase.add(c);
                counter++;
            }
            else
            {
                loopCount++;
                thousandBlocks.add(new limitWrapper(tmpcase,Selected));
                tmpcase = new List<Account>();
                tmpcase.add(c);
                counter = 0;
            }           
        }
       
        if(thousandBlocks.size() == 0)
        {
            loopCount++;
            thousandBlocks.add(new limitWrapper(tmpcase,Selected));
        }
       
        return thousandBlocks;
    }
   
    public class limitWrapper
    {
        public List<Account> cases {get;set;}
         public boolean Selected {get;set;}
        //public integer blockNumber {get;set;}
        public limitWrapper(List<Account> accs, boolean i)
        {
            cases = accs;
            Selected = i;
        }
       
    }
}
Apex Class:

public class mergeAccount {
    
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<wrapAccount> selectedAccounts{get;set;}
    public Boolean bolvar {get; set;}
    public Boolean bolvar1{get;set;}
    public Boolean bolvar2{get;set;} 
    public Boolean bolvar3{get;set;} 
    public String SelectAccount{get;set;}
    public Account objMasterAccount {get;set;}
    public List<SelectOption> lstSelectOption {get;set;}
    public String AccountId;
    public Account objAccount;
    public string AccountName ;
    public ID AccountID1;
    public List<Account> lstAccount = new List<Account>();
    public List<Account> lstAccount1 = new List<Account>();
    public mergeAccount(ApexPages.StandardController controller) {
        
        system.debug('lstAccount'+lstAccount);
        bolvar1 = true;
        bolvar2 = false;
        //objAccount= (Account)Controller.getRecord().id;
        system.debug('objAccount'+objAccount);
        
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap();
            String query='select id';
            for(String s : objectFields.keySet()) {
                if(s != 'Id'){
                    SObjectField test=objectFields.get(s); 
                    //system.debug('test' +test);
                    //if(test.getDescribe().isUpdateable()){ 
                    query += ', ' + s + ' ';
                }
                //}
            }
            
            query +=' FROM Account';
            System.debug(query);
            List<Account> lstAccount = new List<Account>();
            lstAccount = database.query(query);
            //System.debug(lstAccount);
            for(Account a: lstAccount) {
                wrapAccountList.add(new wrapAccount(a,bolvar));
                
                
            }
        }
    }
    
    public void getAccountNames() {
        system.debug('AccountId'+AccountId);
        /*AccountId=Apexpages.currentpage().getParameters().get('id');
        lstAccount1 =[Select id,name from Account where id =:AccountId];
        if(lstAccount1.size()>0)
        {
            AccountName =  lstAccount1[0].Name;
            AccountID1 = lstAccount1[0].id;
            system.debug('AccountName'+AccountName);
        }*/
        
        system.debug('AccountId'+AccountId);
        // selectedAccounts = new List<wrapAccount>();
        lstSelectOption= new List<SelectOption>();
        lstSelectOption.add( new SelectOption('','--Select--'));
        for( wrapAccount wrapacc :  selectedAccounts) {
            lstSelectOption.add( new SelectOption(wrapacc.acc.Id,wrapacc.acc.name));
            
            //lstSelectOption.add(new SelectOption(AccountID1,AccountName));
            system.debug('accOptions'+lstSelectOption);
        }
        
    }
    
    public void nextButton(){
        selectedAccounts = new List<wrapAccount>();
        
        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(new wrapAccount(wrapAccountObj.acc,wrapAccountObj.selected));
                
            }
        }
        getAccountNames();
        bolvar1 = false;
        bolvar2 = true;
        
    }
    
    public PageReference  Selectedmaster(){
        objMasterAccount = new Account();
        objAccount = new Account();
        SobjectField[] fields =  Schema.getGlobalDescribe().get('Account').getDescribe().fields.getMap().values();
        System.debug(fields);
        for(wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id == SelectAccount)
                objMasterAccount = wrapacc.acc;
            //AccountID1 = wrapacc.accId;
            system.debug('objMasterAccount'+objMasterAccount);
        }
        for( wrapAccount wrapacc :selectedAccounts){
            if(wrapacc.acc.id != SelectAccount){
                for(SObjectField field:fields){  
                    if(field.getDescribe().isUpdateable()){   
                        system.debug('masterLead.get(field)'+objMasterAccount.get(field));
                        if(objMasterAccount.get(field)==null && wrapacc.acc.get(field)!=null ){     
                            objMasterAccount.put(field,wrapacc.acc.get(field));
                        }
                    }
                }
            }
        }
        update objMasterAccount;
        bolvar3 = false; 
        PageReference pageRef = new PageReference('/apex/PopUp');
        pageRef.setRedirect(true);
        return pageRef;
    }
    
    public PageReference ok(){
        PageReference pageRef = new PageReference('/001/o');
        pageRef.setRedirect(true);
        return pageRef; 
    }
    
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
        //public id accId {get;set;}
        public wrapAccount(Account a,Boolean bolvar) {
            acc = a;
            selected = bolvar;
            //accId = aId;
        }
    } 
}



Test Class
@isTest
public class mergeAccountTest {
    
    public static testmethod void AccountMergeTest(){
        Map<string, schema.RecordTypeInfo> rtMap = Schema.SObjectType.Account.getRecordTypeInfosByName();
        Id VV=rtMap.get('VV').getRecordTypeId();
        Id MVS=rtMap.get('MVS - Remind A Pet').getRecordTypeId();
        Id VVR=rtMap.get('VVR').getRecordTypeId();
        Id VVANDVVR=rtMap.get('VV and VVR').getRecordTypeId();
        
        
        Account objAccount = new Account();
        objaccount.Name = 'Test';
        objaccount.RecordTypeId =VV;
        insert objAccount;
        
        PageReference pageRef = Page.PopUp;
        Test.setCurrentPage(pageRef);
        
        
        ApexPages.StandardController sc = new ApexPages.standardController(objAccount);
        mergeAccount controller = new mergeAccount(sc);
        Account objacc = new Account();
        Boolean selected = true; 
        controller.bolvar3 = true;
        controller.SelectAccount ='26551025862uiyty';
        
        mergeAccount.wrapAccount wrrap = new mergeAccount.wrapAccount(objacc,selected);
        
        
        controller.nextButton();
        controller.getAccountNames();
         PageReference objPageRef1 = controller.ok();
          for(mergeAccount.wrapAccount wrp : controller.selectedAccounts )
            {
                wrp.selected = true;
            }            
 
        PageReference objPageRef = controller.Selectedmaster();
       
    }
    
}
@isTest
public class OpportunityAmountInWordsTest
{
  
    Public static testmethod void OpportunityAmountInWordsTM()
    {
        RecordType rt = [select id,Name from RecordType where SobjectType='Account' and Name='Supplier' Limit 1];
        Account Acc =New Account();
            Acc.RecordTypeId=rt.id;
            Acc.Name='Test';
            Acc.GST_Reg_No__c='test1';
            Acc.TAX_IDENTIFICATION_NUMBER_VAT__c='Test11';
            Acc.IMPORT_EXPORT_CODE_IEC__c='test12';
            Insert Acc;
       
       Product2 Pro =New Product2 ();
            Pro.Name ='tEST';
            Pro.CurrencyIsoCode='USD';
            Insert Pro;
       Order odd =New Order();
            odd.AccountId=acc.id;
            odd.EffectiveDate=System.today();
            odd.Status__c='Draft';
            odd.Product_Name__c=pro.id;
            odd.Quantity__c=1234;
            odd.Quantity_per_Container__c=23;
            odd.Quantity_per_Packaging_Material__c =55;
            odd.Status='Draft';
            Insert odd;
            
        Opportunity opp =New Opportunity();
            opp.Name='Test';
            opp.accountId = Acc.id;
            opp.CloseDate=system.today();
            opp.CurrencyIsoCode ='USD';
            opp.Worked_by__c='Neha';
            opp.Product_Name__c=pro.id;
            opp.Description_of_Goods__c='test';
            opp.Origin__c='test';
            opp.Packaging_Details__c='trueuus';
            opp.Quantity__c=10000;
            opp.H_S_Code__c='amit';
            opp.Container_Size__c='20 FCL';
            // opp.Agent_Name__c=Customer.id;
            opp.StageName='Enquiry';
            // opp.Agent_Fee_IO__c=123;
            Insert opp;
            
            List<Cost_Price__c> lCostPr = new List<Cost_Price__c>();
            Cost_Price__c Cost1 =New Cost_Price__c();
            Cost1.Opportunity__c=opp.id;
            Cost1.Supplier_Name__c=Acc.id;
            //Cost1.Opportunity__c=opp.Accountid;
            Cost1.Country_of_Final_Destination_Picklist__c='India';
            Cost1.CurrencyIsoCode='USD';
            Cost1.UOM__c='Tonnes';
            cost1.Payment_Status__c = 'DUE';
            cost1.Payment_Receivable_Date__c = System.now().date().addDays(-40);
               
           lCostPr.add(cost1);
            Insert lCostPr;          
           
}
    
}
I have created a 6 objects 
Test1
Test2
Test3
Test4
Test5
Test6

Test6(Lookup with Test5)
Test5(Lookup with Test4)
Test4(Lookup with Test3)
Test3(Lookup with Test2)
Test2(Lookup with Test1)

i want Test1 records in test 6 using soql

Please Help

Thanks,

Regards
Amit Jadhav
Please explain me soql subQuery.
when and how to use it in Apex Code(triggers) ?
in Map and in List
give me some examples
Hi,

I created an email action in the case feed and an apex class to show the default email template, but it doesn't work yet, the template doesn't load.

I have activated the default template checkbox in Support Settings as well, and the template is available for use.

Does anyone know why it doesn't work?

Thanks.

User-added image

User-added image
This is the class:
 
global class E1DefaultTemplateEmail implements Support.EmailTemplateSelector {

    global E1DefaultTemplateEmail() {    }

    global ID getDefaultEmailTemplateId(ID caseId) {

        Case c = [SELECT Subject, Description FROM Case WHERE Id=:caseId];

        EmailTemplate et;

        if (c.subject != null) {
            et = [SELECT id FROM EmailTemplate WHERE DeveloperName = 'E1HC_Send_e_mail_with_case_description'];
        }         

        return et.id;
    }
}

 
My requirement is Display Avg IN Visualforce page 
Field Is a Quantity__c so Show the Average Of Quantity 
I am new when it comes to visualforce and creating custom controllers. 

I have a problem to solve where each Account needs the ability to quickly add an Invoice with only 1 Invoice line item. The ask is to be able to click a button on the Account and be prompted to enter the quantity prior to creating the invoice. 
The result should be after the quantity is entered, an Invoice record is created with 1 Invoice line item showing the fields price and quantity.

Help with how the code should be written would help a lot.

 
for example 
Price__c * Qyt__c = Total_Price__c (Total price is formula field)
Total_Price__c * Disscount_per__c = Disscount__c (Disscount Is also formula field)
Disscount__c + Total_Price__c = Amount (Amount is  also formula field)


how to cover this filed in test class
Controller:

public with sharing class costsheet {
   
    

    public String OrderId;
    public Order ord;
    
    
    public costsheet(ApexPages.StandardController controller) {
      listIex =0.0;
      CFSList =0.0;
      CHAList =0.0;
      CHAListS =0.0;
      ord= (Order)Controller.getRecord();
      OrderId=Apexpages.currentpage().getParameters().get('id');
      system.debug('listStemer>>'+OrderId);
      listStemer=[Select Id,subtotal__c,Supplier_Order__c from Shipper_Info_India__c where Supplier_Order__c =:ord.id AND RecordType.Name='Steamer Charges' limit 1]  ;
      system.debug('listStemer>>'+listStemer);
     if(listStemer.size()>0)
     {
     listIex =listStemer[0].subtotal__c;
     system.debug('listStemer>>'+listIex );
     }
     listCHAChargesR=[Select Id,subtotal__c,Supplier_Order__c  from Shipper_Info_India__c where Supplier_Order__r.id =:ord.id AND RecordType.Name='CHA Charges' AND Bill_Type__c = 'Reimbursement Type'] ;
     if(listCHAChargesR.size()>0)
     {
     CHAList =listCHAChargesR[0].subtotal__c;
     }
     listCHAChargesS=[Select Id,subtotal__c,Supplier_Order__c  from Shipper_Info_India__c where Supplier_Order__r.id =:ord.id AND RecordType.Name='CHA Charges' AND Bill_Type__c = 'Service Type'] ;
     if(listCHAChargesS.size()>0)
     {
     CHAListS =listCHAChargesS[0].subtotal__c;
     }
     listCFSCharges=[Select Id,subtotal__c,Supplier_Order__c  from Shipper_Info_India__c where Supplier_Order__r.id =:ord.id AND RecordType.Name='CFS Charges' limit 1] ;
     if(listCFSCharges.size()>0)
     {
     CFSList =(listCFSCharges[0].subtotal__c).setScale(2);
     }
     
     Calculation();
    
    
    }
    
        public List<Shipper_Info_India__c > listStemer;
        public List<Shipper_Info_India__c > listCFSCharges;
        public List<Shipper_Info_India__c > listCHAChargesR;
        public List<Shipper_Info_India__c > listCHAChargesS;
        public Decimal CFSList {get;set;}
        public Decimal CHAList {get;set;}
        Public Decimal listIex {get;set;}
        public Decimal CHAListS {get;set;}
        public List<Order> ordList = new List<Order>();
        public Decimal TotalAmount_3{get;set;}
        public Decimal TotalFreightAmount_19{get;set;}
        public Decimal TotalFreightAmount_21{get;set;}
        public Decimal TotalFreightAmount_c21{get;set;}
        public Decimal TotalFreightAmount_d21{get;set;}
        public Decimal BasicDuty_c23{get;set;}
        public Decimal BasicDuty_d23{get;set;}
        public Decimal Cess_c24{get;set;}
        public Decimal Cess_d24{get;set;}
        public Decimal TotalCustomDuty_g25{get;set;}
        public Decimal TotalCustomDuty_c25{get;set;}
        public Decimal TotalCustomDuty_d25{get;set;}
        public Decimal ShippingLine_c27 {get;set;}
        public Decimal ShippingLine_d27 {get;set;}
        public Decimal StorageCFS_c32 {get;set;}
        public Decimal StorageCFS_d32 {get;set;}
        public Decimal Others_c30 {get;set;} 
        public Decimal Others_d30 {get;set;} 
        public Decimal Clearing_c31 {get;set;}
        public Decimal Clearing_d31 {get;set;}
        public Decimal TotalC {get;set;}
        public Decimal TotalCost{get;set;}
        public decimal TotalC_c37 {get;set;}
        public decimal TotalC_d37 {get;set;}
        public decimal TotalCost_c38 {get;set;}
        public decimal TotalCost_d38 {get;set;}
        
            
        public void Calculation(){
         TotalAmount_3 = 0;
         TotalFreightAmount_19= 0;
         if(ord.Quantity__c != NULL && ord.Unit_Price__c != null){
            TotalAmount_3 = (ord.Unit_Price__c *ord.Quantity__c).setScale(2);
          }else{
           TotalAmount_3=0;
          }
          if(ord.Total_Insurance__c != null){
          // Need to update this with adding Freight charges
           TotalFreightAmount_19= (ord.Total_Insurance__c+ord.Total_Sea_Freight_Charges__c+TotalAmount_3).setscale(2) ;
           }else{
           TotalFreightAmount_19=0;
           }
           if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalFreightAmount_21 = (TotalFreightAmount_19*ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
            TotalFreightAmount_21=(0+TotalFreightAmount_19).setscale(2);
          }
          if(TotalFreightAmount_19 != 0)
           {
           TotalFreightAmount_c21 = (TotalFreightAmount_21/ord.Quantity__c/1000).setscale(2);
          }
           
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalFreightAmount_d21 = (TotalFreightAmount_c21*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
          TotalFreightAmount_d21=0;
          }
          if(ord.Basic_Customs_Duty_value__c != null)
           {
           BasicDuty_c23 = (ord.Basic_Customs_Duty_value__c/ord.Quantity__c/1000).setscale(2);
          }else{
           BasicDuty_c23=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           BasicDuty_d23 = (BasicDuty_c23*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
           BasicDuty_d23=0;
          }  
          if(ord.Social_Welfare_Surcharge__c != null)
           {
           Cess_c24 = (ord.Social_Welfare_Surcharge__c/ord.Quantity__c/1000).setscale(2);
          }else{
           Cess_c24=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           Cess_d24 = (Cess_c24*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          }else{
           Cess_d24=0;
          }  
          if(ord.Basic_Customs_Duty_value__c != null && ord.Social_Welfare_Surcharge__c != null)
          {
           TotalCustomDuty_g25=(ord.Basic_Customs_Duty_value__c+ord.Social_Welfare_Surcharge__c).setscale(2);
          }else{
            TotalCustomDuty_g25=0;
          }
          if(TotalCustomDuty_g25 != 0)
           {
           TotalCustomDuty_c25 = (TotalCustomDuty_g25/ord.Quantity__c/1000).setscale(2);
          }else{
           TotalCustomDuty_c25 =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalCustomDuty_d25 = (TotalCustomDuty_c25*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           TotalCustomDuty_d25 =0;
          }
          if(listIex != null)
           {
           ShippingLine_c27 = (listIex/ord.Quantity__c/1000).setscale(2);
          }else{
           ShippingLine_c27 =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           ShippingLine_d27 = (ShippingLine_c27*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           ShippingLine_d27 =0;
          }
          if(CFSList != null)
           {
           StorageCFS_c32 = (CFSList/ord.Quantity__c/1000).setscale(2);
          }else{
           StorageCFS_c32 =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           StorageCFS_d32 = (StorageCFS_c32*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           StorageCFS_d32 =0;
          }
          
          if(CHAList != null)
           {
           Others_c30 = (CHAList/ord.Quantity__c/1000).setscale(2);
          }else{
           Others_c30  =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           Others_d30  = (Others_c30 *1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           Others_d30  =0;
          }
          
          if(CHALists != null)
           {
           Clearing_c31 = (CHALists/ord.Quantity__c/1000).setscale(2);
          }else{
           Clearing_c31  =0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           Clearing_d31  = (Clearing_c31 *1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           Clearing_c31  =0;
          }
          
          
          TotalC = (listIex+CHAList+CHAListS+CFSList).setscale(2);
          TotalCost = (TotalC+TotalFreightAmount_21+TotalCustomDuty_g25).setscale(2);
          
          if(TotalC != null)
           {
           TotalC_c37= (TotalC/ord.Quantity__c/1000).setscale(2);
          }else{
           TotalC_c37=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalC_d37= (TotalC_c37*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           TotalC_d37=0;
          }
          
           if(TotalCost != null)
           {
           TotalCost_c38= (TotalCost/ord.Quantity__c/1000).setscale(2);
          }else{
           TotalCost_c38=0;
          }
          if(ord.Exchange_Rate_PO_Currency_to_INR__c != null)
           {
           TotalCost_d38= (TotalCost_c38*1000/ord.Exchange_Rate_PO_Currency_to_INR__c).setscale(2);
          } else{
           TotalCost_d38=0;
          }
          
          
        }
          
       
        
           
      
   //Method to Save Attachments   
    
    public PageReference  SaveAttachmentpdf() {
        system.debug('In save');
        blob pdfBody;
        PageReference thePDF =  new PageReference('/apex/costsheetpdf?id='+OrderId);
        system.debug('ORD--'+OrderId);
        thePDF.setRedirect(true);
           
          if(Test.isRunningTest()) { 
             pdfBody = blob.valueOf('Unit.Test');
            } else {
             pdfBody = thePDF.getContentAsPDF();
           }
            Attachment attach = new Attachment();
            attach.body = pdfBody;
            attach.Name='CostSheetPdf '+System.Now();
            system.debug('OrderId'+OrderId);
            attach.ParentId=OrderId;
            attach.ContentType = 'application/pdf';
            Insert attach;
            
        if (attach == null){
              ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Error will Saving a file .Please check the content of the file'));  
           }
        if (attach != null){
             ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Quote Pdf generated successfully'));
            
          }
      PageReference qtpage = new PageReference('/'+OrderId);
      qtpage.setRedirect(true); 
      
      return thePDF;
   }
This is my class
public with sharing class costsheet {

    

 
 public List<Order> ordwrap {get;set;}
 public List<Opportunity> oppwrap {get;set;}
  public List<SOWrapper> wrapper {get;set;}
 
 
 
 public costsheet()
 {
  ordwrap=[Select id from Order limit 5];
  oppwrap=[select Id,name,Account.Name from opportunity limit 5];
  wrapper = new List<SOWrapper>() ;
        for(Integer i=0 ; i < 5 ; i++)
            wrapper.add(new SOWrapper(ordwrap[i] , oppwrap[i])) ;
  
 }

  
        public class SOWrapper{
        public Order order{get;set;}
        public Opportunity opportunity{get;set;}
        //public Cost_Price__c costprice{get;set;}
        
        public SOWrapper(Order ord, Opportunity opp){
            order= ord;
            opportunity = opp;
            //costprice = cp;
        }
    }
    
}