Friday 27 November 2015

How to get document URL dynamically ?

A we all know sales-force host name (na5,or cs20) used to change from sandbox to production and also when SFDC refresh their server. That is why it is always suggested not to use any hard coded link. Below is code snippet to get document URL dynamically.

 //method to send document link  
    public Static String getDocumentRelativeLink(String documentName){
        String documentURL= '';
        try{
            list<Document> doc = [Select id,Name,SystemModStamp From Document Where Name  = :documentName];
            ID docIds = doc[0].id;
            documentURL = URL.getSalesforceBaseUrl().getProtocol()+'://'+System.URL.getSalesforceBaseUrl().getHost().remove('-api' )+'/servlet/servlet.ImageServer?id='+docIds+'&oid='+userinfo.getorganizationid();
        }Catch(Exception ex){}
        return documentURL ;
    }

OR

 public Static String getDocumentRelativeLink(String documentName){
      
 string baseURL = URL.getSalesforceBaseUrl().toExternalForm();        
        string instanceName;
        String sfdcUrlStrForImage = '';
        integer i;
        string tempInstance;
               try{
            list<Document> doc = [Select id,Name,SystemModStamp From Document Where Name  = :documentName];
         String id = doc[0].id;
         String recordId = id.substring(0,15);
            if(baseURL.contains('cs')){
            i = baseURL.indexof('cs');
            tempInstance = baseURL.substring(i,baseURL.length());
            instanceName = tempInstance.substring(0,tempInstance.indexof('.'));
        }
        else if(baseURL.contains('na')){
            i = baseURL.indexof('cs');
            tempInstance = baseURL.substring(i,baseURL.length());
            instanceName = tempInstance.substring(0,tempInstance.indexof('.'));
        }
        sfdcUrlStrForImage = baseURL.substring(0,i-1)+'c.'+instanceName+'.content.force.com/servlet/servlet.ImageServer?id='+recordId+'&oid='+UserInfo.getOrganizationId()+'&lastMod='+doc[0].SystemModStamp.getTime();
            
        }Catch(Exception ex){}
        return sfdcUrlStrForImage;
    }

Below is the link where I have explained few mistake we do while developing.

http://salesforceworld4u.blogspot.in/2014/04/common-mistake-we-do-while-developing.html

No comments: