Monday, September 28, 2015

How to expose restapi class to the Legacy systems ?

By using @RestResource class and annotations like @httppost, @httpget ,@httpput, @httpdelete..etc

we need to place these annotations before the Methods which we want to expose..

ex:  @RestResource(urlMapping='/Merchandise/*')
global with sharing class MerchandiseManager {
  
    @HttpGet
    global static Merchandise__c getMerchandiseById() {
        RestRequest req = RestContext.request;        
        String merchId = req.requestURI.substring(
                                  req.requestURI.lastIndexOf('/')+1);
        Merchandise__c result = 
                       [SELECT Name,Description__c,Price__c,Total_Inventory__c
                        FROM Merchandise__c 
                        WHERE Id = :merchId];
        return result;
    }
  
    @HttpPost
    global static String createMerchandise(String name,
        String description, Decimal price, Double inventory) {
        Merchandise__c m = new Merchandise__c(
            Name=name,
            Description__c=description,
            Price__c=price,
            Total_Inventory__c=inventory);
        insert m;
        return m.Id;
    }
}

What is UrL class in Sfdc ?

// Create a new account called Acme that we will create a link for later.
Account myAccount = new Account(Name='Acme');
insert myAccount;

// Get the base URL.
String sfdcBaseURL = URL.getSalesforceBaseUrl().toExternalForm();
System.debug('Base URL: ' + sfdcBaseURL );       

// Get the URL for the current request.
String currentRequestURL = URL.getCurrentRequestUrl().toExternalForm();
System.debug('Current request URL: ' + currentRequestURL);        

// Create the account URL from the base URL.
String accountURL = URL.getSalesforceBaseUrl().toExternalForm() + 
                       '/' + myAccount.Id;
System.debug('URL of a particular account: ' + accountURL); 

// Get some parts of the base URL.
System.debug('Host: ' + URL.getSalesforceBaseUrl().getHost());   
System.debug('Protocol: ' + URL.getSalesforceBaseUrl().getProtocol());

// Get the query string of the current request.
System.debug('Query: ' + URL.getCurrentRequestUrl().getQuery());

Sunday, September 13, 2015

Rollup summary for lookup relationship

trigger Rollup on Concur_Reports__c (after insert, after delete, after undelete,after update) {
boolean delflag=false;
Set<Id> crids=new Set<Id>();


Map<Id,List<Concur_Reports__c>> rollup=new Map<Id,List<Concur_Reports__c>>();
List<id> opplist= new List<id>();

if(Trigger.isInsert || Trigger.isUndelete || Trigger.isUpdate ){
For(Concur_Reports__c  con1 : Trigger.new){
crids.add(con1.id);
opplist.add(con1.Opportunity__c);
 if(rollup.containsKey(con1.Opportunity__c)){
rollup.get(con1.Opportunity__c).add(con1);
 }
else{
rollup.put(con1.Opportunity__c,new list<Concur_Reports__c>{con1});
}
}
}
 else if(Trigger.isDelete){
 delflag=True;
 For(Concur_Reports__c con1 : Trigger.old){
crids.add(con1.id);
opplist.add(con1.Opportunity__c);
if(rollup.containsKey(con1.Opportunity__c)){
rollup.get(con1.Opportunity__c).add(con1);
 }
else{
rollup.put(con1.Opportunity__c,new list<Concur_Reports__c>{con1});
}
}
}


    


    system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%'+rollup);


    List<Opportunity> OppUpdateList = New List<Opportunity>() ;


     Map<Id,Opportunity> oppidsfilter=new  Map<Id,Opportunity>([SELECT AccountId,Total_Expense__c,Amount,CampaignId,CloseDate,CreatedById,CreatedDate,CurrentGenerators__c,DeliveryInstallationStatus__c,Description,develoepername__c,ExpectedRevenue,Expense__c,Id,IsClosed,IsDeleted,IsPrivate,IsWon,LastActivityDate,LastModifiedById,LastModifiedDate,LastReferencedDate,LastViewedDate,LeadSource,MainCompetitors__c,Name,NextStep,OrderNumber__c,OwnerId,Pricebook2Id,Probability,RecordTypeId,StageName,SystemModstamp,TotalOpportunityQuantity,TrackingNumber__c,Type FROM Opportunity where id in:opplist]);


   Integer total;


   if(rollup.keyset()!=Null)


   {


  for(Id ids:rollup.keyset())


  {


  total=0;


   List<Concur_Reports__c> cr3=rollup.get(ids);


   Opportunity oppr=oppidsfilter.get(ids);


  


   for(Concur_Reports__c cr4:cr3)


   {
   total=total+Integer.valueof(cr4.ReportTotal__c);


    system.debug('%%%%%%%%%%total%%%%%%%%%%%%'+total);


   }

   if(oppr!=Null){
 if(delflag!=True){
oppr.Expense__c=oppr.Expense__c+total;

  }

  else{

   oppr.Expense__c=oppr.Expense__c-total;


  }


  OppUpdateList.add(oppr);


   system.debug('%%%%%%%%%%OppUpdateList%%%%%%%%%%%%'+OppUpdateList);


    }


  }

try{
    if(OppUpdateList.size()>0){


    Update OppUpdateList;


} else  {

}


}


catch(exception ex){
}


}




 }


Pagination

-----------------------------------------------------------------------------------------------------------------------
Pagination controller

--------------------------------------------------------------------------------------------------------------------------


public with sharing class PagingController {

    List<categoryWrapper> categories {get;set;}

    // instantiate the StandardSetController from a query locator
    public ApexPages.StandardSetController con {      
        get {
            if(con == null) {
                con = new ApexPages.StandardSetController(Database.getQueryLocator([Select Id, Name FROM Account Order By Name Asc limit 100]));
                // sets the number of records in each page set
                con.setPageSize(10);
            }
            return con;
        }
        set;
    }

    // returns a list of wrapper objects for the sObjects in the current page set
    public List<categoryWrapper> getCategories() {
        categories = new List<categoryWrapper>();
        for (Account category : (List<Account>)con.getRecords())
            categories.add(new CategoryWrapper(category));

        return categories;
    }

           
    // indicates whether there are more records after the current page set.
    public Boolean hasNext {
        get {
            return con.getHasNext();
        }
        set;
    }

    // indicates whether there are more records before the current page set.
    public Boolean hasPrevious {
        get {
            return con.getHasPrevious();
        }
        set;
    }

    // returns the page number of the current page set
    public Integer pageNumber {
        get {
            return con.getPageNumber();
        }
        set;
    }

    // returns the first page of records
     public void first() {
         con.first();
     }

     // returns the last page of records
     public void last() {
         con.last();
     }

     // returns the previous page of records
     public void previous() {
         con.previous();
     }

     // returns the next page of records
     public void next() {
         con.next();
     }

     // returns the PageReference of the original page, if known, or the home page.
     public void cancel() {
         con.cancel();
     }
       // displays the selected items
  /*   public PageReference process() {
         for (CategoryWrapper cw : categories) {
             if (cw.checked)
                 ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,cw.cat.name));
         }
         return null;
     } */
       

}
--------------------------------------------------------------------------------------------------------------------------
supporting wrapper class
---------------------------------------------------------------------------------------------------------------------

public class CategoryWrapper {

    public Boolean checked{ get; set; }
    public Account cat { get; set;}

    public CategoryWrapper(){
        cat = new Account();
        checked = false;
    }

    public CategoryWrapper(Account c){
        cat = c;
        checked = false;
    }

   

}


--------------------------------------------------------------------------------------------------------------------------
pagination page
-------------------------------------------------------------------------------------------------------------------------

<apex:page controller="PagingController" tabStyle="Account">
  <apex:form style="style='color: #78bf3a;'" title="Pagination">
    <apex:pageBlock title="Pagination"  >

      <apex:pageBlockButtons location="top">
     <!--   <apex:commandButton action="{!process}" value="Process Selected"/> -->
        <apex:commandButton action="{!cancel}" value="Cancel" style="color:#78bf3a;font-weight: normal;font-size:15px;height:30px;text-align:center;font-weight:bold;font-family:Arial,Helvetica,sans-serif;"/>
      </apex:pageBlockButtons>
      <apex:pageMessages />

      <apex:pageBlockSection title="Category Results -  Page #{!pageNumber}" columns="1">
        <apex:pageBlockTable value="{!categories}" var="c">
          <apex:column width="25px">
            <apex:inputCheckbox value="{!c.checked}"/>
          </apex:column>
          <apex:column value="{!c.cat.Name}" headerValue="Name"/>
        </apex:pageBlockTable>
      </apex:pageBlockSection>
    </apex:pageBlock>

    <apex:panelGrid columns="4">
    <apex:commandLink action="{!first}">First</apex:commandlink>
    <apex:commandLink action="{!previous}" rendered="{!hasPrevious}">Previous</apex:commandlink>
    <apex:commandLink action="{!next}" rendered="{!hasNext}">Next</apex:commandlink>
    <apex:commandLink action="{!last}">Last</apex:commandlink>
    </apex:panelGrid>

  </apex:form>
</apex:page>

Dynamic Search Engine

-----------------------------------------------------------------------------------
Controller

------------------------------------------------------------------------------------


public class SearchEngine1 {

    public String name { get; set; }
   
    public String firstname {get;set;}                                    
 
   public String LastName{get;set;}  
   public String Title{get;set;}  
    public List<contact> searchResults {get;set;}
    private boolean firstFilterApplied = false;
   
    public SearchEngine1(){
        searchResults = new List<contact>();
    }

    public PageReference search(){
        searchResults.clear();
        firstFilterApplied = false;
        try{
            //Create the dynamic SOQL query
           
            String queryString = 'SELECT FirstName,LastName,Title '+ 'FROM contact';
   
         
           
            if (LastName!= null && LastName!= ''){
                LastName= String.escapeSingleQuotes(LastName); //To avoid SOQL injection
               
                LastName= lastname.startsWith('%') ? LastName: '%' + LastName;
                LastName= lastname.endsWith('%') ? lastname : lastname + '%';
               
                queryString += whereOrAndClause() + ' LastName like \''+LastName+'\'';
            }
             system.debug('##########'+queryString );
         
         
           
           
            searchResults = Database.query(queryString);
            system.debug('##########'+searchResults);
        }
        catch(QueryException e){
            //If the query returns more than 1000 records, display an error to the user
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'No records found with this criteria'));
            return null;
        }
        catch(Exception e1){
             ApexPages.addMessages(e1);
             return null;
        }      

        if (searchResults.size() == 0){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'No records found with this criteria'));
        }
               
        return null;

    }
   
     
 
   
    private String whereOrAndClause(){
        String queryClause;
        if (firstFilterApplied){
            queryClause = ' AND ';
        }
        else{
            queryClause = ' WHERE ';
        }
        firstFilterApplied = true;
        return queryClause;
    }
}



---------------------------------------------------------------------------------------------------------------
Dynamic Controller Page
-------------------------------------------------------------------------------------------------------------

<apex:page controller="SearchEngine1" tabStyle="Account" showHeader="true" sidebar="true" >
    <apex:form >
        <apex:pageMessages />
        <apex:pageBlock title="Search Criteria">
             <apex:pageBlockSection >
           
                   <apex:inputText value="{!LastName}" label="Last Name"/>
       
               
            </apex:pageBlockSection>
           
           
           
            <apex:pageBlockButtons location="bottom">
                    <apex:commandButton action="{!search}" value="Search"/>
            </apex:pageBlockButtons>
           
           
        </apex:pageBlock>
       
       
        <apex:pageBlock title="Search Result">
            <apex:pageBlockTable value="{!searchResults}" var="res" rendered="{!searchResults.size > 0}">
                <apex:column title="Final result">
                    <apex:outputLink value="/{!res.Id}" target="_blank">{!res.FirstName}</apex:outputLink>
                </apex:column>    
               
                 <apex:column title="Final result">
                    <apex:outputLink value="/{!res.Id}" target="_blank">{!res.LastName}</apex:outputLink>
                </apex:column>    
               
                 
               <!-- <apex:column title="Celebrity">
                    <apex:outputLink onmouseover="" value="/{!res.LastName__c}" target="_blank">{!res.celebrity__r.name}</apex:outputLink>
                </apex:column> -->
             
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>  
</apex:page>


Tuesday, August 25, 2015

PASSING PARAMETERS from one vf to another vf



Many a times you would want to pass parameters to a visualforce page..
There are a number of Situations in which you would want this. This article covers a few of them.
Scenario 1 - From a Custom Button. 
When you create a custom button on "Account",  you will only have the option of selecting Visualforce pages that have the "standardcontroller="Account"" attribute.

To overcome this restriction, select the content source as URL and not visualforce... Then you could type the URL as \apex\yourpage.. And what more you can now pass parameters as you need using merge fields... This method has got one more advantage.. You are not forced to use a standard controller with an extension just for your page to appear in the list when you actually do not need a standard controller.. 



Situation 2 - From a Link.
When you want to pass parameters between visualforce pages use the <apex:param> tag....

Here is a small sample program

Step 1: Create a Visualforce page called SamplePage1....

<apex:page >
<apex:outputlink value="/apex/SamplePage2"> Click Here <apex:param name="msg" value="success"/> </apex:outputlink>
</apex:page>

Step2:  Create a Visualforce page called SamplePage2

<apex:page controller="Sampleclass"> </apex:page>

Step 3:  On SamplePage1 Click on the " Click Here" link. You will see that when you click on the link you will navigate to the SamplePage2. Check the URL now..

https://na5.salesforce.com/apex/SamplePage2?msg=success

You can see that the parameter " msg" with value "success" has been passed to the new page.

Pagereference().getParameters().put()

PageReference is a type in Apex. Read the documentation here. 

When you click a command button or a command link in a visualforce page, you call a method. The return type 
of this method would be a PageReference meaning that, after clicking the button the user will be redirected to a 
new Page. Below is a sample code, which shows how to pass parameters from a PageReference

public Pagereference gotonewpage()
{     
     PageReference pageRef = Page.existingPageName;
     pageRef.getParameters().put('msg','success');
     return PageRef
}

existingPageName - actual name of a visualforce page

Retrieve Parameter Values in Apex Class:

The Apex Class code would be 

public class Sampleclass
{
Public String message = System.currentPagereference().getParameters().get('msg');
}

So now, the variable "message" would store the value of your parameter "msg"....

How to Cover this code in TEST Method?????


public class Sampleclass{Public String message = System.currentPagereference().getParameters().get('msg');public static testmethod void SampleclassTest(){System.currentPagereference().getParameters().put('msg','success');}}


Using Param

how can we pass the id of the contact to the controller? The answer is straightforward, but requires a slight mindshift. 

The <apex:param> standard component allows parameters to be defined for a parent component, which can be assigned to a controller property. I can therefore change my markup to the following to specify the parameter:
?



<apex:commandButton value="Del" action="{!delCont}" rerender="all">  <apex:param name="contIdParam" value="{!cont.id}" assignTo="{!contIdChosen}"/>
</apex:commandButton>


Note the rerender attribute of the commandbutton - if this attribute is not present, the parameter does not get sent back to the controller. I simply have an outputpanel around the entire page contents.


I then add the following property to my controller:

1
public String contIdChosen {get; set;}


The key to this is the behaviour when the button is clicked - the id of the contact instance is assigned to my controller property before the action method is invoked. Thus the method that is actually carrying out the delete can simply access the contIdChosen property secure in the knowledge that it will contain the id of the contact associated with the button:

public PageReference delCont()
{
 Contact toDel=new Contact(id=contIdChosen);

 delete todel;

 setupContacts();

 return null;
}

  


The fact that I have to rerender in order to get the parameter passing to work is the reason why I maintain the list of Contacts independent of the Account record from the standard controller - I can't make the browser refresh the page and thus rebuild the related contacts from scratch, so I have to rebuild the list server side.


Through URL


You can simply pass the parameters through the URL.
say you are redirecting from one VF page to another
string value = 'your param value';
string url;
url = '/apex/VF_Page_Name?param1=' + value; 

PageReference pageRef = new PageReference(url);
pageRef.setRedirect(true);
return pageRef;
Then in the controller of the VF page, you just can get the param like this

String param_value = system.CurrentPageReference.GetParameters().get('param1');

Monday, August 24, 2015

Preventing duplicates by checking two fields

---------------------------------------------------------------------------------------------------------------------

Scenario: Single Contact should not add same Date more than Once.
              This scenario is based on Timesheet filling... system   should not allow user to add                     same date again and again

___________________________________________________________________________________



trigger DuplicateCheckTrigger on Timesheet__c (before insert) {
       Set<string> nameSet = new Set<string>();
     
       Map<id,Date> dtr=new  Map<id,Date>();
       map<Id,List<Timesheet__c>> avoiddups=new map<Id,List<Timesheet__c>>();

        for(Timesheet__c times : trigger.new){
  if(!dtr.containskey(times.ContactId__c)){

  dtr.put(times.ContactId__c,times.StartDate__c);
  }
 
            nameSet.add(times.ContactId__c );      
         
        }

   

      system.debug('%%%%%%%%%%%%%nameSet%%%%%%%%%%%%%%'+nameSet);
        List<Timesheet__c> timList = new List<Timesheet__c>(
            [select id,ContactId__c , StartDate__c,ContactId__r.name from Timesheet__c where ContactId__c in:nameSet]);

            system.debug('%%%%%%%%%%%%%timList%%%%%%%%%%%%%%'+timList);
         
        for(Timesheet__c timess : timList){

     
        if(avoiddups.containskey(timess.ContactId__c)){
   avoiddups.get(timess.ContactId__c).add(timess);
   }
   else{
   avoiddups.put(timess.ContactId__c,new List<Timesheet__c>{timess});
 
   }
}
system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%'+avoiddups.values());
system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%'+dtr.values());
  For(Timesheet__c str:trigger.new)
  {
    For(Timesheet__c dt:avoiddups.get(str))
    {
 
     if(dt.StartDate__c==dtr.get(str.ContactId__c))
     {
   
     system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%%'+dt.StartDate__c+'^^^^^^^^^^^^^^^^^^^^^^^^'+dtr.get(str.ContactId__c));
   
     str.StartDate__c.adderror('This date is already specified to this contact: '+dt.ContactId__r.Name);
     }
 
 
    }


  }


}