Friday, September 25, 2015

Real Time Scenario ::Pagination with check box and selected record can download into Excel format.

Display the all records in one visualforce page(with pagination)  user can select the records with check box,and click on next button i will select some more records in next pagination and click button.the selected records can download into Excel Format.

Visualforce page 1

<apex:page controller="insuranceClaimdownload" showHeader="false" >
  <script type="text/javascript">
        
        function doCheckboxChange(cb,itemId){

            if(cb.checked==true){
                aSelectItem(itemId);
            }
            else{
                aDeselectItem(itemId);
            }

        }

    </script>
 <apex:form >
     <!-- handle selected item -->
        <apex:actionFunction name="aSelectItem" action="{!doSelectItem}" rerender="pb">
            <apex:param name="contextItem" value="" assignTo="{!contextItem}"/>
        </apex:actionFunction>

        <!-- handle deselected item -->
        <apex:actionFunction name="aDeselectItem" action="{!doDeselectItem}" rerender="pb">
            <apex:param name="contextItem" value="" assignTo="{!contextItem}"/>
        </apex:actionFunction>

    <apex:pageBlock id="pb" title="Insurance Claims Details">
        <apex:pageBlockButtons >
            <apex:commandButton value="Download" action="{!downloadInsClaims}"/>
        </apex:pageBlockButtons>
        <apex:pageBlockTable value="{!insClaiDowload}" var="p" title="insClaiDowload">
                   <apex:column >
                     <apex:facet name="header">Action</apex:facet>
                     <apex:inputCheckbox value="{!p.IsSelected}" onchange="doCheckboxChange(this,'{!p.insClaim.Id}')"/>
                   </apex:column>
                   <apex:column value="{!p.insClaim.Client_Urn__c}"/>
                   <apex:column value="{!p.insClaim.name}"/>
                   <apex:column value="{!p.insClaim.Status__c}"/>
                   <apex:column value="{!p.insClaim.RecordTypeId}"/>
                   <apex:column value="{!p.insClaim.ClaimSubmittedToInsDate__c}"/>      
        </apex:pageBlockTable>
        <apex:commandLink action="{!doPrevious}" rendered="{!hasPrevious}" value="Previous" />
        <apex:outputLabel rendered="{!NOT(hasPrevious)}" value="Previous" /> &nbsp;
        <apex:commandLink action="{!doNext}" rendered="{!hasNext}" value="Next" />
        <apex:outputLabel rendered="{!NOT(hasNext)}" value="Next" />
    </apex:pageBlock>
 </apex:form>
</apex:page>

Controller::

public class insuranceClaimdownload {
    public ApexPages.StandardSetController setCon;
    public String contextItem{get;set;}
    public Set<Id> selectedInsClaimIds;
    public List<Insurance_Claim__c> selectedInsClaims{set;get;}
    public List<Insurance_Claim__c> UpdateList{set;get;}
    public insuranceClaimdownload (){
       selectedInsClaimIds=new Set<Id>();
       setCon=new ApexPages.StandardSetController([select id,name,Rejected_Reason__c,ClaimSubmittedToInsDate__c ,Client_Urn__c,RecordTypeId,Rejected_Date__c,Status__c from Insurance_Claim__c]);
       setCon.setPageNumber(1);
       setCon.setPageSize(2);
      
    }
     public void doPrevious(){

        if(setCon.getHasPrevious())
            setCon.previous();

    }
     public void doNext(){

        if(setCon.gethasNext())
            setCon.next();

    }
     public Boolean getHasPrevious(){

        return setCon.getHasPrevious();

    }
     public Boolean getHasNext(){

        return setCon.getHasNext();

    }
    // pageblackTable method
   
    public List<insClaimWra> getinsClaiDowload(){
     
           List<insClaimWra> insRows=new List<insClaimWra>();
           
           for(sObject r : setCon.getRecords()){
               Insurance_Claim__c claim=(Insurance_Claim__c)r;
               insClaimWra row = new insClaimWra(claim,true);
              if(this.selectedInsClaimIds.contains(claim.Id)){
                row.IsSelected=true;
            }
            else{
                row.IsSelected=false;
            }
              insRows.add(row);
           }    
     
       return insRows;
    }
    // commonad button method
    Public PageReference downloadInsClaims(){
        selectedInsClaims= new List<Insurance_Claim__c>();
        UpdateList= new List<Insurance_Claim__c>();
        for(Insurance_Claim__c insclaims:[select id,name,Rejected_Reason__c,Client_Urn__c,ClaimSubmittedToInsDate__c ,RecordTypeId,Rejected_Date__c,Status__c from Insurance_Claim__c where id in:selectedInsClaimIds]){
           selectedInsClaims.add(insclaims);
           Insurance_Claim__c ins=new Insurance_Claim__c(id=insclaims.id);
           ins.ClaimSubmittedToInsDate__c=system.today();
           UpdateList.add(ins);
        }
        Database.update(UpdateList);
        PageReference secondPage = new PageReference('/apex/insuranceClaimdownloadpage');
        secondPage.setRedirect(false);
        system.debug('selectedInsClaims################'+selectedInsClaims);
        return secondPage;
       

    }
    // pageblockTable method for insuranceClaimdownloadpage
    public List<Insurance_Claim__c> getdownLoadRecordlist(){
      return selectedInsClaims;
    }
     public void doSelectItem(){

        selectedInsClaimIds.add(contextItem);

    }
     public void doDeselectItem(){

        selectedInsClaimIds.remove(contextItem);

    }
    public  class insClaimWra{

        public Insurance_Claim__c insClaim{get;set;}
        public Boolean IsSelected{get;set;}

        public insClaimWra(Insurance_Claim__c c, Boolean s){
            insClaim=c;
            IsSelected=s;
        }

    }
}

Second VIsualForce page

<apex:page controller="insuranceClaimdownload" showHeader="false" contenttype="application/x-excel#filename{!TODAY()}.xls" >
  <!-- contenttype="application/x-excel#filename{!TODAY()}.xls" --->
  <apex:form >
     <apex:pageBlock >
         <apex:pageBlockTable value="{!downLoadRecordlist}" var="insc" border="1" columnsWidth="100px,200px,150px" cellspacing="0" cellpadding="8">
            <apex:column headerValue="Clien Urn" value="{!insc.Client_Urn__c}"/>
            <apex:column headerValue="Insurance NO" value="{!insc.name}"/>
            <apex:column headerValue="Status" value="{!insc.Status__c }"/>
            <apex:column headerValue="FileDownloadDate" value="{!insc.ClaimSubmittedToInsDate__c }"/>
           
         </apex:pageBlockTable>
     </apex:pageBlock>
  </apex:form>
</apex:page>

Test class;;


@isTest()
public class insuranceClaimdownload_test{
   static testMethod void main(){
          Product2 prd=new Product2();
            prd.Name='Jana Kisan - Mixed Farming';
            prd.Category__c='Others';
            prd.IsActive=True;
            prd.Maximum_Grace_Period_in_Days__c='7';
            prd.Maximum_Interest_Variance__c=26;
            prd.Maximum_Loan_Amount__c=200000;
            prd.Minimum_Grace_Period_in_Days__c='7';
            prd.Minimum_Installment__c=20000;
            prd.Minimum_Interest_Variance__c=24;
            prd.Minimum_Loan_Amount__c=40000;
            prd.Minimum_Term__c='24';
            prd.Net_Cash_Flow_120_EMI_required__c=false;
            prd.ProductCode='891';
            prd.Rate_of_Interest__c=24;
            prd.Tenure__c =24;
            prd.EMI_Post_15__c=0;
            prd.EMI_Pre_15__c=0;
            prd.PRODUCT_CODE__c=891;
            Insert prd;
        prd=[SELECT id,PRODUCT_CODE__c FROM Product2 WHERE Id=:prd.Id];
        System.assertEquals(prd.PRODUCT_CODE__c,891);
        Zone__c zon=new Zone__c();
            zon.Name='Central';
            zon.Zone_Code__c=9;
            zon.Owner__c='central HEAD';
            zon.Sponsor_Bank_Id__c='DCB';
            insert zon;
        zon=[SELECT id,Name FROM Zone__c WHERE Id=:zon.Id];
        System.assertEquals(zon.Name,'Central');
        
        Region__c  reg=new Region__c();
            reg.Name='HARYANA';
            reg.Region_Code__c=9;
            reg.Zone_Code__c =zon.Id;
            reg.Owner__c='HARYANA HEAD';
            Insert reg;
            
        Branch__c bran = new Branch__c();
            bran.Name = 'KB Sandra';
            bran.Branch_Code__c = '1234';
            bran.Region_Code__c=reg.Id;
            bran.Red_flagging_for_Agro_Loan__c=True;
            bran.Classification__c='Branch';
            bran.Owner__c='Manoj';
            Insert bran;
        bran=[SELECT id,Name FROM Branch__c WHERE Id=:bran.Id];
        System.assertEquals(bran.Name,'KB Sandra');
        
        Area__c area1 = new Area__c();
        area1.CurrencyIsoCode='INR';
        area1.Name='blre';
        area1.Area_Code__c=1232;
        area1.Branch_Codes__c=bran.id;
        insert area1;
        
        NCO__c ncoObj = new NCO__c(name= 'ncoName');
        insert ncoObj ;
        
        Account acc =new Account();
            acc.CIS_No_new__c='123154';
            acc.RecordTypeId =RecordTypeUtil.recordTypeId('Account','JanaKisan Draft'); 
            acc.Area_lookup__c = Area1.ID;
            acc.Customer_Id__c='1233212344327896';
            acc.Branch_Name__c= bran.ID;              
            acc.First_Name__c='Surender';              
            acc.Name = 'kaus';  
            acc.LastName__c = 'Manu';            
            acc.Last_Name_CO__c='Choudhary';
            acc.MotherTongue__c= 'Hindi';
            acc.Salutation__c = 'Mrs.';
            acc.DO_You_Have_Mobile_No__c = 'Yes';
            acc.DO_You_Have_Land_Line_No__c = 'No';
            acc.DOB_Borrower__c=date.newInstance(1980,3,3);              
            acc.Sex__c='F';     
            acc.Father_OR_Husband__c='Husband';              
            acc.Father_Husband_s_First_Name__c='ap';              
            acc.F_H_s_Last_Name__c='pa';
            acc.Opted_for_NPS_Lite__c = 'No';         
            acc.Marital_Status__c='Married'; 
            acc.Main_Product_or_Service_sold__c = 'yes';
            acc.Industry = 'Government';
            acc.Brief_Description_of_Occupation_words__c = 'jsdhfk';                                         
            acc.IdentityProof__c='PAN';  
            acc.Aadhar_Card__c = 'No';            
            acc.IdentityProofNo__c= 'EDCBA1234E';              
            acc.Religion__c='Hindu';              
            acc.Caste__c='Others';              
            acc.Natureofemployment__c='Salaried';
            acc.NCO_Occupation_Code__c = ncoObj.id;                    
            acc.Length_of_business_serviceYears__c=9.1;  
            acc.Months1__c=11;              
            acc.Current_JobBusinessYears1__c=3;              
            acc.Months2__c=11;              
            acc.Gross_Annual_Income__c=12321.50;              
            acc.Mobile_NO_Contact__c='9876543210';              
            acc.OWN_PP__c='PP';              
            acc.Door_No_Main_Borrower__c='4';              
            acc.Street_Name_main__c='13';              
            acc.Pin_COntacts__c='123211';              
            acc.City_Borrower__c='chd';        
            acc.No_of_Groups_Attached__c=5;            
            acc.No_of_Years_in_Current_Residence__c =3;   
            acc.Mobile_No__c='1234567895'; 
            acc.Mobile__c = '5987654321';  
            acc.Net_Cash_Flow__c=50000.00;
            acc.Landmark_contacts__c = 'Bangalore';
            acc.Address3__c = 'address11';
            //acc.Distance_between_Facilitator_and_Client__c=10.0;
            insert acc;
            
        Secondary_Customer_Details__c  c = new Secondary_Customer_Details__c();
            c.Account__c = acc.id;
            c.Name = 'Vikram';
            c.Last_Name__c = 'Reddy';
            c.FatherOrHusband__c = 'Father';
            c.Date_of_Birtht__c = date.newinstance(1960, 2, 17);
            c.Mother_Tongue__c = 'Telugu';
            c.Marital_Statuss__c = 'Single';
            c.Identity_Proofs__c = 'PAN';
            c.Identity_ProofNo__c = 'APAPT1670C';
            c.FH_FirstName__c = 'Test';
            c.FH_LastNames__c = 'Test';
            c.Gender__c = 'M';
            c.Educations__c = 'Illiterate';
            c.Type_of_Relation__c = 'Husband';
            c.Nature_of_Employment__c='Not-Employed';
            insert c;
       
        
      
                
       
        Application__c ap=new Application__c();
            ap.Name='JKApplication';
            ap.Product__c=prd.Id;
            ap.Initial_Total_Loan_Amount__c=200000;
            ap.Application_Category__c='Other';
            ap.GVR_Score__c=1200;
            ap.Branch__c=bran.Id;
            ap.Date_Time_of_Enrollment__c=System.Today();
            ap.Place_of_Enrollment__c='Branch';
            ap.Repayment_Date__c='10';
            ap.Tenure_Months_EFS__c = 24;
            ap.Area__c = area1.id ;
            ap.Application_Type__c='New';
            ap.Application_Category__c = 'Agro';
            ap.Application_Status__c='Draft';
            ap.RecordTypeId = RecordTypeUtil.recordTypeId('Application__c','JanaKisan Data Entry');
            ap.All_sanction_conditions_met__c = false; 
            insert ap;
            
            List<Opportunity> oplist = new List<Opportunity>();
                
               
                    Opportunity opp = new Opportunity ();
                    opp.StageName='Open';
                    opp.recordtypeId = RecordTypeUtil.recordTypeId('Opportunity','JanaKisan CBCheck'); 
                    opp.Name ='891';
                    opp.Credit_Bureau_Status__c='Accept';
                    opp.Product_Name__c=prd.Id;
                    opp.Opp_Selected__c = false;
                    opp.AccountId=acc.ID;
                    opp.Tenure_Months__c = 24 ;
                    opp.ForecastCategoryName = 'Commit';        
                    opp.Secondary_Customer_Details__c=c.ID;
                    opp.Name='891';
                    opp.Product_Code__c = 891 ;
                    opp.Loan_Cycle__c = 'K1';
                    opp.Application__c = ap.Id;
                    //opp.CloseDate=date.parse('03/03/2016');
                    opp.CloseDate=System.Today();
                    opp.No_of_Family_Members__c=4;
                    opp.Status__c='Active';
                    opp.Loan_Amount__c='40000';                
                    insert opp;
       List<Insurance_Detail__c> idetails1=new List<Insurance_Detail__c>();
      
       Insurance_Detail__c idetails=new Insurance_Detail__c();
       
       idetails.Date_Of_Tagging__c=date.parse('03/05/2016');
       idetails.Status__c='Form Verified';
       idetails.RecordTypeId= RecordTypeUtil.recordTypeId('Insurance_Detail__c','LiveStock Initial DE');       
       idetails.Insured_For__c=opp.id;
       insert idetails;
        
         Insurance_Claim__c Inscl=new Insurance_Claim__c();
         Inscl.Breed__c='somescus';
         Inscl.Death_due_to__c='accident';
         Inscl.Insurance_Detail__c=idetails.id;
         Inscl.First_Name__c='buffalo ';
         Inscl.District__c='bangalore';
         Inscl.Place_Of_Death__c='bangalore';
         Inscl.Policy_Number__c='jli0004543';
         Inscl.Tag_Number__c='jfs23456';
         
           
                 insert Inscl;
                  Attachment attach1=new Attachment();    
                   attach1.Name='Unit Test Attachment';
                   Blob bodyBlob1=Blob.valueOf('Unit Test Attachment Body');
                   attach1.body=bodyBlob1;
                  attach1.parentId=Inscl.id;
                  insert attach1;
                  
        Test.startTest();
              Id ClaimIntimation = RecordTypeUtil.recordTypeId('Insurance_Claim__c','Claim Intimation');
              Id ClaimSubmittedtoOpps = RecordTypeUtil.recordTypeId('Insurance_Claim__c','Claim Submitted to Opps');
              Id ClaimReceivedatOps = RecordTypeUtil.recordTypeId('Insurance_Claim__c','Claim Received at Ops');
              Id ClaimSubmittedToIns = RecordTypeUtil.recordTypeId('Insurance_Claim__c','Claim Submitted to Ins');
              ApexPages.StandardController stdController = new ApexPages.StandardController(Inscl);
              insuranceClaimdownload ext = new insuranceClaimdownload();
              List<insuranceClaimdownload.insClaimWra> wrp = ext.getinsClaiDowload();
              wrp[0].Isselected=true;
              
              ext.doNext();
              ext.getHasNext();
              ext.setCon.next();
              
              ext.getHasPrevious();
              ext.doPrevious();
              ext.setCon.previous();
              
              ext.getinsClaiDowload();
              ext.downloadInsClaims();
              ext.doSelectItem();
              ext.doDeselectItem();
              ext.getdownLoadRecordlist();
             /*
              ext.SelectedinsClaim();
              Inscl.Status__c='ClaimReceivedatOps';
              Inscl.RecordTypeId=ClaimSubmittedtoOpps;
              Inscl.attachment_attached__c=true;
              update Inscl;
              Inscl.RecordTypeId=ClaimReceivedatOps;
              Inscl.Document_Comments__c='images';
              Inscl.Documents_Checklist__c='good';
              update Inscl;
              Inscl.Status__c='Claim settled by Ins';
              Inscl.RecordTypeId=ClaimSubmittedToIns;
              Inscl.Upload_Date__c=Date.Today();
              update Inscl;
              Inscl.Status__c='ClaimReceivedatOps';
              Inscl.RecordTypeId=ClaimSubmittedToIns;
               update Inscl;
               */
         Test.stopTest();
   }
}


Sunday, September 20, 2015

Programmatically Creating Sharing Rules with Apex

Bussiness:

   When i Creating Contact,i selected check box true(Make_Public__c) the Record is share with Other group in Organization.

   if Make_Public__c it is False,delete the sharing record.

Contact is Private in OWD.



trigger ContactMakePublicTrigger on Contact (after insert, after update) {

  // get the id for the group for everyone in the org
  ID groupId = [select id from Group where Type = 'Organization'].id;

  // inserting new records
  if (Trigger.isInsert) {

    List<ContactShare> sharesToCreate = new List<ContactShare>();// sharing object of contact

    for (Contact contact : Trigger.new) {
      if (contact.Make_Public__c == true) {

        // create the new share for group
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = contact.Id;
        cs.UserOrGroupId =  groupId;
        sharesToCreate.add(cs);

      }
    }

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  // updating existing records
  } else if (Trigger.isUpdate) {

    List<ContactShare> sharesToCreate = new List<ContactShare>();
    List<ID> shareIdsToDelete = new List<ID>();

    for (Contact contact : Trigger.new) {

      // if the record was public but is now private -- delete the existing share
      if (Trigger.oldMap.get(contact.id).Make_Public__c == true &amp;&amp; contact.Make_Public__c == false) {
        shareIdsToDelete.add(contact.id);

      // if the record was private but now is public -- create the new share for the group
      } else if (Trigger.oldMap.get(contact.id).Make_Public__c == false &amp;&amp; contact.Make_Public__c == true) {

        // create the new share with read/write access
        ContactShare cs = new ContactShare();
        cs.ContactAccessLevel = 'Edit';
        cs.ContactId = contact.Id;
        cs.UserOrGroupId =  groupId;
        sharesToCreate.add(cs);

      }

    }

    // do the DML to delete shares
    if (!shareIdsToDelete.isEmpty())
      delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = 'Manual'];

    // do the DML to create shares
    if (!sharesToCreate.isEmpty())
      insert sharesToCreate;

  }

}

============Test Class==============
@isTest
private class TestContactMakePublicTrigger {

    // test that newly inserted records marked as pubic=true have corresponding shares created
    static testMethod void testAddShares() {

    Set<ID> ids = new Set<ID>();
    List<Contact> contacts = new List<Contact>();

    for (Integer i=0;i<50;i++)
      contacts.add(new Contact(FirstName='First ',LastName='Name '+i,
        Email='email'+i+'@email.com',Make_Public__c=true));

    insert contacts;

    // get a set of all new created ids
    for (Contact c : contacts)
      ids.add(c.id);

    // assert that 50 shares were created
    List<ContactShare> shares = [select id from ContactShare where 
      ContactId IN :ids and RowCause = 'Manual'];
    System.assertEquals(shares.size(),50);

    }

    // insert records and switch them from public = true to public = false
    static testMethod void testUpdateContacts() {

    Set<ID> ids = new Set<ID>();
    List<Contact> contacts = new List<Contact>();

    for (Integer i=0;i<50;i++)
      contacts.add(new Contact(FirstName='First ',LastName='Name '+i,
        Email='email'+i+'@email.com',Make_Public__c=false));

    insert contacts;

    for (Contact c : contacts)
      ids.add(c.id);

    update contacts;

    // assert that 0 shares exist
    List<ContactShare> shares = [select id from ContactShare where 
      ContactId IN :ids and RowCause = 'Manual'];
    System.assertEquals(shares.size(),0);

    for (Contact c : contacts)
      c.Make_Public__c = true;

    update contacts;

    // assert that 50 shares were created
    shares = [select id from ContactShare where ContactId IN :ids and RowCause = 'Manual'];
    System.assertEquals(shares.size(),50);

    for (Contact c : contacts)
      c.Make_Public__c = false;

    update contacts;

    // assert that 0 shares exist
    shares = [select id from ContactShare where ContactId IN :ids and RowCause = 'Manual'];
    System.assertEquals(shares.size(),0);

    }
}

Trigger to share the record level access to User.


    trigger Account_PrivateAttachmentSharing on Account (after update)
{
  /*
    When the Owner of an Account is changed, create
    a sharing rule for each associated Private Attachment record.   
  */
  Set<Id> accIdSet = new Set<Id>();
  for (Account acc : Trigger.new)
  {
    if (acc.OwnerId != Trigger.oldMap.get( acc.Id ).OwnerId)
    {
      accIdSet.add(acc.Id);
    }
  }
 
  if (accIdSet.size() == 0)
  {
    return;
  }
 
  //## get all private attachments related to all of the opps...
  Map<Id, List<Private_Attachments__c>> accIdPAMap =
          new Map<Id, List<Private_Attachments__c>>();
 
  List<Account> accWithPAList = [Select Id, Name, OwnerId,
        (Select Id From Private_Attachements__r)
        From Account o
        WHERE o.Id IN :accIdSet];
 
  /*     
  List<Private_Attachment__c> paList = [SELECT Id, Name
          FROM Private_Attachment__c
          WHERE Opportunity__c IN :oppIdSet];
  */

  List<Private_Attachments__Share> paShareInsertList =
          new List<Private_Attachments__Share>(); 
  for (Account accpa : accWithPAList)
  {
    List<Private_Attachments__c> paList = accpa.Private_Attachements__r;
    if (paList != null && paList.size() > 0)
    {
      for (Private_Attachments__c pa : paList)
      {
        //## have to update PAs for this Opp...
        Private_Attachments__Share pashare = new Private_Attachments__Share();
        pashare.ParentId = pa.Id;
        pashare.UserOrGroupId = accpa.OwnerId;
        pashare.AccessLevel = 'Edit'; 
        paShareInsertList.add(pashare);
      }
    }
  }
 
  System.Debug('    #### paShareInsertList: '+paShareInsertList);
  //PrivateAttachmentOwnership.insertRecords(paShareInsertList);
  try
  {
    Database.insert(paShareInsertList, false);
  }
  catch (Exception e)
  {
    //## an error will be thrown if it's a dup record...
  }

}

Saturday, September 19, 2015

Sharing Rule Throw Batch Apex for Account Object


global class AccountPlanSharing_Batch implements Schedulable, Database.Batchable<sObject> {

    global static void scheduleJob() {
        // 1st digit = seconds
        // 2nd digit = minutes
        // 3rd digit = hours (24 hours)
        // 4th digit = day of month (? = no value, * = all, 1 - 31)
        // 5th digit = month (? = no value, * = all, 1=January, etc.)
        // 6th digit = day of week (? = no value, * = all, 1=Sunday, etc.)

        String sch_1stDayofMonth_1am = '0 0 2 * * ?'; // 2am every day
        System.schedule('AccountPlanSharing_Batch' + (Test.isRunningTest() ? 'TEST' : ''),
            sch_1stDayofMonth_1am, new AccountPlanSharing_Batch());    
    }

    public String qrystr = 'SELECT Id, Name, RecordType.Name, Account__r.Name, Account__r.CP_Hierarchy_Level_Type__c '+
            ' From Account_Plan__c '+
            ' WHERE RecordType.Name = \'EMEA Account Plan\' '+
            ' AND Account__r.CP_Hierarchy_Level_Type__c = \'RP\' ';
           
    public void setQrystr(String instr) {
        qrystr = instr;
    }
       
    /**
     * Constructor
     * - Does nothing because nothing to do for scheduled job
     */
    global AccountPlanSharing_Batch(){
    }
   
    /**
     * Schedule Interface Method
     * Responsible for starting the job (not batched though)
     */
    global void execute(SchedulableContext sc) {
        Database.executeBatch(new AccountPlanSharing_Batch(), 100);
    }

    global void finish(Database.BatchableContext BC){ }

    global Database.QueryLocator start(Database.BatchableContext BC){
        // Select all Accounts and process
        return Database.getQueryLocator(qrystr);
    }

    global void execute(Database.BatchableContext BC, list<sObject> scope){
        runJob(scope);
    }
   
    /*
      main method...
    */
    public static void runJob(list<sObject> scope) {
        System.Debug('    #### runJob...');
        // set of RP Account Ids for the AccountPlans in scope
        Set<Id> rpAccountIdSet = new Set<Id>();
        for (sObject sobj : scope) {
            Account_Plan__c acctplan = (Account_Plan__c) sobj;
            rpAccountIdSet.add(acctplan.Account__r.Id);
        }
       
        // now query all child MP Account records
        List<Account> acctList = [SELECT Id, Name, OwnerId, Owner.Name, ParentId
                  FROM Account WHERE ParentId IN :rpAccountIdSet AND CP_Hierarchy_Level_Type__c = 'MP'];
       
        // build a Map of RP Account Id to List<MP Account>
        Map<Id, List<Account>> acctRPMPMap = new Map<Id, List<Account>>();
        for (Account acct : acctList) {
          List<Account> tmpacctList = new List<Account>();
          if (acctRPMPMap.containsKey(acct.ParentId)) {
            tmpacctList = acctRPMPMap.get(acct.ParentId);
          }
          tmpacctList.add(acct);
          acctRPMPMap.put(acct.ParentId, tmpacctList);
        }
       
        // now for each AP, grab cooresponding MP Accounts and build sharing record
        List<Account_Plan__Share> apshareInsertList = new List<Account_Plan__Share>();
        for (sObject sobj : scope) {
            Account_Plan__c acctplan = (Account_Plan__c) sobj;
            List<Account> mpList = acctRPMPMap.get(acctplan.Account__c);
            if (mpList != null) {
        for (Account acct : mpList) {
          String acctOwner = acct.OwnerId;
          if (acctOwner.startsWith('005')) {
            Account_Plan__Share apshare = new Account_Plan__Share();// sharing object of account
            apshare.ParentId = acctplan.Id;// parent id
            apshare.UserOrGroupId = acct.OwnerId;
            apshare.AccessLevel = 'Read';
            apshareInsertList.add(apshare);
            System.Debug('    #### creating apshare for '+acct.Owner.Name+' for '+acctplan.Name);
          }
        }
            }
        }
       
        Database.insert(apshareInsertList, false);
   
    }

   

}

Friday, September 18, 2015

How to Implement One-to-One Relationship for Lookup and Mater-Details

 FOR LOOKUP:::

STEP 1: Create one custom field in Child Object with Uniq option.

STEP2:CREATE WorkFlow Rule on Child object and Criteria is Created or edited .

  In fields:select the Parent is notnull click on save&next button.

STEP3: Choose field update option.
STEP4: Choose use-formula: and select the parentobject  and click on save and active the Workflow.

  MASTERDETAILS:

  Create Rollupsummay field on Parent  and write validation if Roll up summary is greater than one throw error message

Saturday, September 12, 2015

custome button open popup window by using jquery

Real Time Scenario: When user Submitting Application /Sent back Reasons business need Reasons for why user submitting/Sent back Reasons,user enter some comments on field..

  instead of showing error message by using jquery when user click on button open DailgBox, in dialog box user enter comments and click on OK button Record will updated with comments and Record moved to another record type.

   1.create custom button (out of 3 check box select 2nd one)
     

2.Past the bellow code and change as per your Requirement:


  {!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}
{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')}
{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js')}
var newRecArray = []; // variable declaration
try{
jQuery(function() { // jquery starting

jQuery('head').append('<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/start/jquery-ui.css" type="text/css" />');// css library

 var html ='<div id="dialog" title="Enter Comment"> <textarea id="txtn" rows="4" cols="30" id="rsn"></textarea></div>'; // html to enter capture the data
 if(!jQuery('[id=dialog]').size()){
 jQuery('body').append(html);
 } // adding html to jquery

    var recordtype= sforce.connection.query("SELECT Name, id from RecordType WHERE Name='nnr' And SobjectType='nnr__c'"); //query of recordtype id
    var records = recordtype.getArray("records"); // get recordtype id
    var appRec = new sforce.SObject("nnr__c"); // instance creation of sobject
    appRec.Id= "{!nnr__c.Id}";
   
   


 jQuery( "#dialog" ).dialog({
 autoOpen: true,
 modal: true,
 show: {
 effect: "bounce",
 duration: 200
 },
 hide: {
 effect: "bounce",
 duration: 200
 },
 buttons: {
 "Ok": function() {
    var sbComment= $('#txtn').val();
    if(sbComment.length > 0){
   
    appRec.RecordTypeId=recordtype.records.Id;
   
    appRec.status__c=sbComment;
   
    newRecArray.push(appRec);
    result=sforce.connection.update(newRecArray);

    jQuery( this ).dialog( "close" );
    window.location.reload();
    }else{
    alert("Please Enter Sent Back Reason");
    }

 },
 Cancel: function() {
 jQuery( this ).dialog( "close" );
 }
 }
 });
 });
}
catch(e){
alert('An Error has Occured. Error: ' + e);
}  
  

Custome Button to Update RecordType and custome field

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}
var newRecArray = [];
var recordtype= sforce.connection.query("SELECT Name, id from RecordType WHERE Name='nnr' And SobjectType='nnr__c'");// query for record type
var records = recordtype.getArray("records"); // execute the query

var appRec = new sforce.SObject("nnr__c");// instance for sobject
appRec.Id= "{!nnr__c.Id}"; // assign id
appRec.RecordTypeId=recordtype.records.Id;
appRec.status__c='good';//
newRecArray.push(appRec);// javascript method to add into arry
result=sforce.connection.update(newRecArray);// updating record
 document.location.reload(true)// reload the page

how to call apex call from custom button to pass the values from custome button

Custom Button code:

  {!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

var meetingID = '{!nnr__c.Id}';
var agree = confirm("Are you sure you want to proceed ");
if(agree){
   

    var result = sforce.apex.execute("YourClassName ","Methodname",{meetingID: meetingID});
   
    alert(result);
   
    }

=======================
Apex Class code

*************************
global class YourClassName
{
webservice static OppResult Methodname(ID meetingID) // you can pass parameters
    {
        OppResult res = new OppResult();

            
         
           res.errorMsg = 'oh no something broke';

            res.oppId = '01pW00000000000';

            

            system.debug(res);

            return res;
    }
    global class OppResult{

           webservice String errorMsg;

           webservice Id oppId;

       }
   
}

custome button in pagelayout to check filed condtion then it link to your visualforce page visualforce page

{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}

var s="{!nnr__c.Application_Status__c}";
var p="{!nnr__c.Application_Category__c}";

if(s=='Sanctioned' && p==' Group') {
window.open("/apex/yourVFPAGE?id={!Application__c.Id}");
}
else {
alert("Insufficient privileges, You are not authorized to download the application.");

}