Skip to main content

Posts

Showing posts from 2015

How to create a case record from a VF page and attach a particular file to the record?

Below is code snippet for the same. VF Page:- <apex:page controller="creatingcaseAttachment">   <apex:form >       <apex:pageBlock title="Customer Issue">                  <apex:pageBlockSection title="Case Creation ">               <apex:inputField value="{!customerCase.accountid}"/>                 <apex:inputField value="{!customerCase.contactId}"/>                 <apex:inputField value="{!customerCase.Origin}"/>                 <apex:inputField value="{!customerCase.Status}"/>                 <apex:inputField value="{!customerCase.Reason}"/>               <apex:inputField value="{!customerCase.Subject}"/>   ...

How to remove particular key from a map?

This is pretty simple one, One of my friend asked me how to remove a particular key-value pair from a map. Below is code snippet for the same. Hope It will help all. Map<String, String> colorCodes =   new Map<String, String>(); colorCodes.put('Red', 'FF0000'); colorCodes.put('Blue', '0000A0'); colorCodes.put('Blue2', '0000A0'); // If you know the key then just use like below      colorCodes.remove('Blue2'); System.debug('printing=== '+colorCodes); // if you are not sure what about the key or need some manipulation then follow below approach for(String key:colorCodes.keySet().clone()) {     // myMap.get(key), process that value     colorCodes.remove('Blue2'); } System.debug('printing==ater= '+colorCodes);

How to get sandbox name in apex?

As we all know sandbox username looks like " behera@mycompany.com.dev  " dev- is the sandbox name, How can we get it this dynamically ? Use below code :- if( UserInfo.getUserName().substringAfterLast('.com') != null)                     contact.Email = contactInfo.Email+'.'+ UserInfo.getUserName().substringAfterLast('.') ;                 else                     contact.Email = contactInfo.Email; } UserInfo.getUserName().substringAfterLast('.') - will give you sandbox name. UserInfo.getUserName().substringAfterLast('.com') will tell you whether anything is there after " .com ". if not there that means we are in production otherwise in sandbox.  We can also used same method to identify type of org like prod or non prod. There is another approach for this.  Organization org = [select id,IsSandbox fro...

Workaround for COMPILE ERROR: Field is not writeable: Account.IsPartner

As part of my requirement, I had to create an account making isPartner as true, Unfortunately I got this   COMPILE ERROR: Field is not writable: Account.IsPartner  Then I first inserted that account then updated isPartner as true. Account acc = new Account(name = 'Asish'); insert acc; System.debug('Inserted account Ispartner ---'+acc.Ispartner); acc.Ispartner = true; update acc; System.debug('Inserted account---'+acc); For more info on Ispartner field--   https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_account.htm

How to make java script function will execute after the controller method executed?

As we all know java script function will execute first then controller method executes, In some case we need java script method should execute first. Below is the work around for this case. Instead of normal java script we will use on load java script which means when page loads/refresh that java script function will execute. Again it will be problem because each and every time that method will execute. How to avoid this ? We will use a Boolean variable to control execution. public Boolean isJavascriptInvoked {         get {             if (null == this.isJavascriptInvoked ) {                 this.isJavascriptInvoked = false;                         }             return this.isJavascriptInvoked ;         }         set;     } public PageReferen...

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 ...

How to find duplicates element from a list?

This is an interview question one of my colleague asked, so thought of sharing. Below is code snippet List<String> stringList = new List<String>{'One','two','Three','Four','One','two'}; set<String> setString = new set<String>(); set<String> duplicatesetString = new set<String>(); for(String s:stringList ){     if(!setString.add(s)){       duplicatesetString .add(s);    } } System.debug('duplicatelistString----'+duplicatesetString ); System.debug('duplicatelistString----'+duplicatesetString.add('ten'));

How to make Case comments as Private?

Hi All, Sometimes we don't want to display all the case comments to be visible in the portal page. A customer should see his comments and the agent's comments in the portal page. Internal user's like R&D department comments should not be visible. For that I have created a workflow to achieve this. Case comments is a child object of Case, "Is-published" is the field which specifies comments as private or public. Is-published is true means comments must be public otherwise it will be private.

How to use Like Operator in SOSL

Hi All, I have already explained about the LIKE operator in my earlier post. http://salesforceworld4u.blogspot.in/2013/08/like-operator-in-salesforce_13.html Some asked how to use Like operator in SOSL, Below is the some code snippet where Like operator being used in SOSL. Lets find account,contact,lead and opportunities records whose name is containing test keyword List<List<SObject>> searchList = [FIND 'Test*' IN ALL FIELDS RETURNING Account (Id, Name WHERE Name LIKE '%test%' limit 10),Contact(Id, Name WHERE Name LIKE '%test%' limit 10),Opportunity(Id, Name WHERE Name LIKE '%test%' limit 10),Lead(Id, Name WHERE Name LIKE '%test%' limit 10)]; Account [] accounts = ((List<Account>)searchList[0]); System.debug('Printing size-- '+accounts.size()); System.debug('Printing size-- '+accounts ); Contact [] contacts = ((List<Contact>)searchList[1]); System.debug('Printing size-- '+contacts....

How will external system get SFDC service endpoint URL dynamically

Hi All, This post is all about to avoid an integration issue(Service not available or invalid session id) when instance url get changed in SFDC. From SFDC side no need to perform any action ,but we can suggest appropriate approach of fetching endpoint url to external system so that communication will be smoother. For an inbound integration SFDC has to provide two WSDL to external system. Partner WSDL (Required to generate session id ) Service WSDL In the service wsdl the endpoint URL will be <soap:address location=" https://cs15.salesforce.com/services/Soap/class/YourWebserviceClassName "/> So the external system will add endpoint URL in a property file or in some in configuration stuff, that is how webservice works.As we all know instance ( cs15 ) used to change from environment to environment (QA to UAT), and instance will  also change when SFDC plan for refreshment of server. At that time we have to update external team about the new url otherwise the...

How to make pageblock section to be collapsed by default

Hi All, We can achieve it through java script. <apex:page standardController="Account"> <apex:form> <apex:pageBlock id="block1">     <apex:pageBlockSection id="section1" columns="2" collapsible="true" title="Collapsebale Section">         <apex:inputField value="{!Account.Name}"/>          <apex:inputField value="{!Account.Phone}"/>     </apex:pageBlockSection>      <script> twistSection(document.getElementById('{!$Component.block1.section1}').getElementsByTagName('img')[0]) </script> </apex:pageBlock> </apex:form> </apex:page> Normal Section Collapsed Section  

How to Override Go button in SFDC(Overriding List view In SFDC )

Hi All, I had come across a scenario like to override a button so called "Go" in standard page.As we all know,when Go button clicked,it will always navigate to sfdc standard list view. What if you want to navigate to your custom page? How can we achieve it? It is very easy, please go through below image.

Hyperlink formula is not working(Instance URL is getting appended along with the external link)

HI Guys, This post is regarding an issue i had come across at my development work. I had to display a hyper link to navigate to some other site from a standard layout. That link varies from record to record. So I created a text field(Brass_Link__c) to store the link and created a hyperlink formula field(Brass_Hyper_formula__c) to display "view " as link if text field is having some value. Below is the formula field logic IF(BRASS_Link__c <> null, HYPERLINK( BRASS_Link__c , "View"), "") BRASS_Link__c - Stores link  How will we solve above issue? Its quite simple change the link from www.google.com to  https://www.google.com

How to wrap page block title in a single line?

Hi All, This is so simple .You have to just include some css code in the VF page. </script>     <style>               .pbTitle {         white-space: nowrap             }     </style> Thank you very much.

How to control two batch job execution ?

We are all familiar with batch class in SFDC. This  post is all about to discuss a known issue in batch class and what is workaround for that? As we know batch class is is required when we are dealing with large number of records and total number of batch job will be decided based on scope parameter (defined while calling a batch class) and total number of records. Say total number of records = 100 Scope parameter = 5.  Database.executeBatch(new batchclass(),5); Then batch job will be 20 which means each job will process 5 records. We can see how many jobs are pending and how many jobs completed in set up-->apex jobs. While one batch is in progress we invoke same batch class another time having batch size 5 and total number of records 50. Ideally number jobs should be 10 but actually it will be 10 + number of progressing job of previous batch. Which causes data redundancy that means same records will be processed two times in both the batch.This is the known issue...

UNABLE_TO_LOCK_ROW Error during deployment.

Hi All, I came across an issue ( UNABLE_TO_LOCK_ROW ) while deploying and validating change set. As you know all the test classes run when a change set is validated or deployed,one of the test class was throwing UNABLE_TO_LOCK_ROW exception. How will you handle above exception? Ans- Setup--Develop-- Apex Test Execution--Click Options--Checked Disable Parallel Apex Testing.

Passing JavaScript in Page reference method.

The below post is all about closing child window and refreshing parent window after updating record. http://salesforceworld4u.blogspot.in/2015/06/closing-child-window-and-refreshing.html But let's think there is a requirement like we have to validate before updating and closing child window then above approach wont work. For the above requirement we have to pass javascript code in pagereference method instead of calling javascript on button click. public PageRefeRence savingAccount(){         PageRefeRence pageRef ;         if(account.name == ''){             ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Error,'You must enter some value...');             ApexPages.addMessage(myMsg);         }         else{             upsert account;           }   ...

Closing the child window and Refreshing parent window.

As we all know there are many window properties are available so it is quite easy even i had thought same thing but while implementing i faced many issue so i thought of sharing . Below are few window property which are useful. ·          window.opener  refers to the window that called  window.open( ... )  to open the window from which it's called ·          window.parent  refers to the parent of a window in a  <frame>  or  <iframe> ·          window.top  refers to the top-most window from a window nested in one or more layers of  <iframe>  sub-windows. Lets say there is button on account "Change Account Name" ,On clicked one popup is opening and which would allow you to change Account name and one button "Save" is there in popup window. On clicked child window will be closed and acco...

How to schedule one class to run in every 1 mins?

Sometimes we need to run a class in every minute to do some operation.     // This section of code will schedule the next execution 1 minutes from now    global class Scheduling_Svc_WS_CreateBatch implements Schedulable{  // Execute method     global void execute(SchedulableContext SC) {          datetime nextScheduleTime = system.now().addMinutes(1);          string minute = string.valueof(nextScheduleTime.minute());          string second = string.valueof(nextScheduleTime.second ());          string cronvalue = second+' '+minute+' 0-23 * * ?' ;          string jobName = 'selfReschedulingClass ' +nextScheduleTime.format('hh:mm');          Scheduling_Svc_WS_CreateBatch p = new Scheduling_Svc_WS_CreateBatch();           system.schedule(jobName, cronvalu...

How to check accessibility of an user on a particular record ?

It is a very challenging requirement, Generally we will update records through trigger for complex requirement.  Lets think a scenario where we have to update a particular field value(say field name-IsUpdate) on an Opportunity and few profile is having editable access to that field,there is a already a trigger written for other purpose(updating some other thing) on Opportunity,So we have to modify same trigger and add our logic in that trigger. Our first and foremost approach  would be checking profile name in the condition as below. Approach-1(Using profile) Assume that profile "Test_profile_name" is having editable access to that field(IsUpdate) Profile ProfileName = [select Name from profile where id = :userinfo.getProfileId()]; for(Opportunity opp:trigger.new){      if(profileName.Name.containsIgnoreCase('Test_profile_name')){               // opp.IsUpdate = true;      } } It will work fine n...

How to call apex class from process builder?

As we all know it is not possible to invoke apex class from work flow,for that purpose sfdc lunched new functionality called process builder. Please go through this link. In my previous post i have explained about creation of process builder and updating a field through process builder. http://salesforceworld4u.blogspot.in/2015/04/updating-records-thorough-lightening.html Now this is post is all about calling an apex class from process builder. public class DeleteBrassCaseUtil{    @InvocableMetho d(label='Get Brass Cases Names' description='Returns the list of Brass Cases corresponding to the specified Brass Cases IDs.')   public static void deleteBrassCase(List<Id> BrassCaseIds)     {         List<BRASS_Case__c> brassCases =[SELECT Id,Is_Org_Case_Created__c...