Friday, 22 August 2014

Streaming API Salesforce

The Force.com Streaming API lets you expose a near real-time stream of data from the Force.com platform. Administrators can create topics, to which applications can subscribe, receiving asynchronous notifications of changes to data in Force.com, via the Bayeux Protocol. Streaming data made simple, secure  and scalable.

Before Digging Deep into the Logic First Download the Following Zip Files and Upload them in Static Resources
There are 3 steps in creating Real Time Notifications Using Streaming API

1) Upload files in static Resources
2) Build a query of fields you want to access and create your pushtopic.
3) Write Your logic for handling the notifications received.

1) Upload files in static Resources : -

Download Below rar file, extract and Upload each file. Remember What you are naming while uploading as you need to access this files in your vf page.

Click To Download

2) Build a query of fields you want to access and create your pushtopic : -

Query

The first step in using the Streaming API is to define a SOQL query that will return the records you are interested in. For example, your application may require a notification whenever a new Account is created. A suitable query might be:
1SELECT Id, Name FROM Account
Alternatively, you might only be interested in Accounts with more than 1,000 employees:
1SELECT Id, Name FROM Account WHERE SomeField> 1000
As a special case, you can specify a record id in the WHERE clause and receive notifications whenever any change occurs on that record:
1SELECT Id, Name FROM Account WHERE Id = '001x0000002JSofAAG'
These are just some simple examples - see the Streaming API documentation for a full discussion of Streaming API queries.

PushTopic

Once you have decided on your query, it's time to create a PushTopic that binds a topic name to the query. You can set the following fields on the PushTopic record:
Field NameTypeExampleDescription
ApiVersiondouble23.0Required. API version to use for executing the query specified in Query.
DescriptionstringAll records for the Account object.Optional. Description of what kinds of records are returned by the query.
NamestringNewAccountsRequired. Descriptive name of the PushTopic. The maximum length is 25 characters.
QueryStringSELECT Id, Name FROM AccountRequired. The SOQL query statement that determines which record changes trigger events to be sent to the channel. Maximum length is 400 characters.
There are also several system fields on PushTopic such as CreatedById and SystemModstamp.
As soon as you create a PushTopic record, applications can subscribe to the topic.
Go ahead and create a topic now. Login to your Developer Edition environment, Go to Developer console and navigate to Execute Anonymous Block and copy paste below code.
 PushTopic pushTopic = new PushTopic();  
 pushTopic.Name = 'new account'; // you can specify name of your choice  
 pushTopic.Query = 'SELECT Id, Name FROM account';  
 pushTopic.ApiVersion = 31.0;  
 pushTopic.NotifyForOperationCreate = true;  
 pushTopic.NotifyForOperationUpdate = true;  
 pushTopic.NotifyForOperationUndelete = true;  
 pushTopic.NotifyForOperationDelete = true;  
 pushTopic.NotifyForFields = 'Referenced';  
 insert pushTopic;  
3) Write Your logic for handling the notifications received: -

Visual Force page Code :-
 <apex:page showHeader="false" standardController="Account" extensions="streamingcontroller" id="page" >  
 <!-- the static resource files uploaded-->  
   <apex:includeScript value="{!$Resource.cometd}"/>  
   <apex:includeScript value="{!$Resource.jquery}"/>  
   <apex:includeScript value="{!$Resource.json2}"/>  
   <apex:includeScript value="{!$Resource.jquery_cometd}"/>  
   <apex:includeScript value="/support/console/25.0/integration.js"/>  
   <script type="text/javascript">  
     (function($)  
     {  
       $(document).ready(function() {  
         // Connect to the CometD endpoint  
         $.cometd.init({  
           url: window.location.protocol+'//'+window.location.hostname+'/cometd/24.0/',  
           requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}  
         });  
         // Subscribe to a topic. JSON-encoded update will be returned in the callback  
         // In this example we are using this only to track the generated event  
         $.cometd.subscribe('/topic/newaccount', function(message)  
         {  
           //You can use message as it will return you many attributes  
           //I am just using to track that event is generated  
           RefreshedAccounts();  
         });  
       });  
     })(jQuery)  
   </script>  
  <apex:form id="form" style="padding:0px;margin:0px;">  
  <apex:actionFunction name="RefreshedAccounts" action="{!newaccountlist}" reRender="block">  
  </apex:actionFunction>  
   <apex:pageBlock mode="maindetail" id="block">  
    <apex:pageblockTable value="{!myaccounts}" var="a">   
    <apex:column width="50%" >  
    <apex:outputField value="{!a.name}" id="name" />  
    </apex:column>  
   </apex:pageblockTable>  
   </apex:pageBlock>  
  </apex:form>  
 </apex:page>  
Controller Code :-
 public class streamingcontroller{  
   public streamingcontroller(ApexPages.StandardController controller) {  
    storinglist = new list<account>();  
   }  
 //variables declaration  
 public list<account> storinglist{set;get;}  
   //get method of list  
   public list<account> getmyaccounts(){  
      storinglist= [select id,name from account order by id desc];  
   return storinglist;  
   }  
   public void newaccountlist(){  
   getmyaccounts();  
   }  
 }  

Hope this Helps..

Wednesday, 20 August 2014

Look up field for Multiple Sobjects in VisualForce page

Hi,Have you gone through task fields ? There we will have a Single lookup field "WhoId" which works for both Contact as well as Leads. Thought of Implementing this Logic in VisualForce.Here we need two vf pages  and controllers to do so.MultipleLookup is page 1 and controller :- Parent Page lookuppage is page 2 and controller :- Child Page So lets start with parent page, In this page we will have 3 fields 1)Hidden field:- To store the Id of the record(As relationship fields need ID to save) 2)Pick List :- To store Sobjects you wish to provide 3) Input text :- To display label of record selected. Below is the Page 1 Code : -
 <apex:page controller="multiplelookup" showHeader="false">  
 <script> var newWin=null;  
 function openLookupPopupipd(name, id,val){  
 if(val.value != ''){  
         var url="/apex/lookuppage?namefield=" + name + "&idfield=" + id+"&sobject="+val.value;  
  newWin=window.open(url, 'Popup','height=700,width=1200,left=100,top=100,resizable=no,scrollbars=yes,toolbar=no,status=no');  
         if (window.focus){  
           newWin.focus();  
         }  
         return false;  
         }  
         else{  
         }  
       }   
       function closeLookupPopup(){  
         if (null!=newWin){            
         newWin.close(); }   
       }   
     </script>  
  <apex:form >  
  <apex:pageBlock >  
   <apex:pageBlockSection >  
   <apex:outputPanel >  
    <apex:inputhidden value="{!hiddenval}" id="hiddenid"/><br/>  
    <apex:outputLabel >Field</apex:outputLabel>   
    <apex:selectList size="1" value="{!selectedsobject}" label="Select Sobject"   
    onchange="openLookupPopupipd('{!$Component.labeltoshow}','{!$Component.hiddenid}',this); return false">  
    <apex:selectOptions value="{!allsobjects}"></apex:selectOptions>  
   </apex:selectList><apex:inputText value="{!showinglabel}" id="labeltoshow"></apex:inputtext>  
   </apex:outputPanel>  
   </apex:pageBlockSection>  
  </apex:pageBlock>  
  </apex:form>  
 </apex:page>  
Controller 1 Code : -
 public class multiplelookup {  
 //variable declaration  
 public string hiddenval{set;get;}  
 public string showinglabel{set;get;}  
 public string selectedsobject{set;get;}  
   //constructor  
   public multiplelookup (){  
   }  
    //method which gets list of sobjects  
   public list<SelectOption> getallsobjects(){  
   Map<String, Schema.SObjectType> demomap= Schema.getGlobalDescribe();  
   Schema.DescribeSObjectResult[] descResult =Schema.describeSObjects(new String[]{'Account','Contact','Lead','Opportunity'});  
   List<SelectOption> options = new List<SelectOption>();  
     options.add(new SelectOption('','--None--'));  
   for(integer i=0;i<=descResult.size()-1;i++){  
   DescribeSObjectResult sobjectRes = descResult[i].sObjectType.getDescribe();  
   system.debug('sobjects:::::'+sobjectRes );  
   options.add(new SelectOption(sobjectRes.getName(),sobjectRes.getName()));  
   }  
     return options;  
   }  
 }  
Now Page 1 is ready.. Now lets see What is happening on selection of Sobject from Picklist. Onselection a Javascript function named "openLookupPopupipd"  is invoked along with 3 parameters.  1)Hidden Field ID 2)InputText Field ID 3) Sobject we select from picklist. Page 2 :- Page 2 Contains list of records of sobjects we have selected from page 1. It is a Dynamic list, and gets loaded based on sobject  selected Page 2 Code: -
 <apex:page controller="lookuppage" showHeader="false">  
 <script language="javascript">  
   window.onload = new function()   
   {  // bring popup window to front  
    window.focus();   
  var ele=document.getElementById('{!$Component.form.block.section.query}');  
    if (ele)   { ele.focus();   }  }  
   function fillIn(name, id)  {    
    var winMain=window.opener;if (null==winMain)  {      
     winMain=window.parent.opener;    
     }    
      var ele=winMain.document.getElementById('{!$CurrentPage.parameters.namefield}');  
     ele.value=name;  
     ele=winMain.document.getElementById('{!$CurrentPage.parameters.idfield}');  
    ele.value=id;   
    ele.focus();  
    winMain.closeLookupPopup();  
    }  
   </script>  
 <apex:form >  
  <apex:pageBlock mode="maindetail" id="show">  
  <apex:pageMessage severity="error" summary="No Matcing Data Found" rendered="{!showerror}"></apex:pageMessage>  
   <apex:pageblocksection >  
   <apex:pageBlockTable value="{!listofrecords}" var="rec">  
    <apex:column value="{!rec.id}" rendered="{!IF(Fields.size == 0 , true, false)}"/>  
    <!--<apex:column value="{!rec.name}" /> -->  
    <apex:repeat value="{!Fields}" var="FieldLable">   
      <apex:column rendered="{!IF(FieldLable != ' ' , true, false)}" >  
       <apex:outputLink value="#" onclick="fillIn('{!rec[FieldLable]}', '{!rec.id}')" >{!rec[FieldLable]}</apex:outputLink>   
      </apex:column>   
         </apex:repeat>       
   </apex:pageBlockTable>  
   </apex:pageblocksection>   
  </apex:pageBlock>  
 </apex:form>  
 </apex:page>  
Controller 2  Code :-
 public class lookuppage {  
 public list<sobject> records{set;get;}  
 public boolean showerror{set;get;}  
 public List<string> fields{private set;get;}  
 public string selectedsobject{get;set;}   
   public lookuppage(){  
   selectedsobject = System.currentPageReference().getParameters().get('sobject');  
   if(selectedsobject == '' || selectedsobject ==null) {  
   showerror = true;  
   }  
   else{  
   showerror = false;  
   }  
   records = new list<sobject>();  
   fields = new List<string>();  
   }  
   public list<sobject> getlistofrecords(){  
    try{  
   fields = new list<string>();  
    Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();   
    Schema.SObjectType systemObjectType = gd.get(selectedsobject);  
    Schema.DescribeSObjectResult r = systemObjectType.getDescribe();   
    Map<String, Schema.SObjectField> M = r.fields.getMap();   
      for(Schema.SObjectField s: M.values()){  
      Schema.DescribeFieldResult fieldResult = s.getDescribe();   
     if( fieldResult.getName()=='Name'){  
     fields.add(fieldResult.getName());  
     }  
      }  
      system.debug('fields::::::::::'+fields);  
      String query='select Id' ;  
      for(string field : fields){  
      if(field.toLowerCase() != 'id' )   
       query+= ','+ field + ' ' ;   
      }  
    query+= ' from ' + selectedsobject+ ' LIMIT 100' ;  
    system.debug('Query:::::::::'+query);  
    records = Database.query(query);  
     system.debug('queried records::::::::::'+records);  
     return records;  
    }  
    catch(exception e){  
    return null;  
    }  
   }  
 }  

Friday, 11 July 2014

Refresh Parent Window after Closing Child Window Salesforce

                 Hi, Recently had a requirement to perform multiple actions in a single page. First taught of using Modal POPUPS as they are simple and easy to work. But due to salesforce date field not showing in popup issue had to modify it from popup's to multiple windows/pages.

                Later came to know I have opened window successfully but how to refresh parent window after closing this child window. Bang.. How ??? 

              Finally with a bit of  Java script  code i  found solution in this requirement.

Parent Page vf code :-

 <apex:pageblockTable var="all_stud" value="{!allStudents}" >  
     <apex:column headerValue="Student Name">  
         <apex:outputLink value="#" onclick="openLookupPopup('{!all_stud.name}', '{!all_stud.id}')" >{!all_stud.name}</apex:outputLink>  
    <!--here onclick i am invoking a javascript function,  
     in this function i am passing two parameters name,and id. You can customize as you need-->  
     </apex:column>  
  </apex:pageblockTable>   

Here is the java script of parent page :-

 <script>  
       var newWin=null;  
       function openLookupPopup(name, id){  //function for opening page
 // specify the URL of page you want to open  
         var url="/apex/quickregister?namefield=" + name + "&id=" + id;  
         newWin=window.open(url, 'Popup','height=700,width=1200,left=100,top=100,resizable=no,scrollbars=yes,toolbar=no,status=no');  
         if (window.focus){  
           newWin.focus();  
         }  
         return false;  
       }     
       </script>  
        <script>  
       function reload() {  //this is function used to refresh parent page
       reloadparent();  
       }     
     </script>  
Now let's move to child page :-

perform the action you want to and add this script to close child window
 <script>  
  function closeaftersave(){  
   var winMain=window.opener;  
    if (null==winMain)  
    {  
      winMain=window.parent.opener;  
    }  
   winMain.reload();//this is the function of parent page which gets invoked from child page  
   window.top.close();// this line just closes the window opened  
   }  
 </script>  
 <apex:form>  
     <apex:page:block>  
      <apex:commandButton value=" Button " action="{!myaction}" oncomplete="closeaftersave()"  />  
     </apex:pageblock>  
 </apex:form>  

What is the problem Now.. Child page is closing successfully but why is parent page not getting refreshed ??

Paste this line of code in parent page outside of pageblock table. It will through an error if it's inside the table
  <apex:actionFunction name="reloadparent" action="{!reload}" />  
 <!--specify rerender if want to refresh only a particular area of page-->  
<!--Note: the name of actionFunction should be same of function within reload function-->

Controller Code:- of parent //i haven't specified any logic here you can work on your own, it just refreshes my page
 public void reload(){  
 }  


Hope This helps.. Happy Coding..!

Sunday, 29 June 2014

Serialize apex class to JSON salesforce

Developing an JSON output from apex class is always a challenging task for new comers. So, I have decided to post a simple apex class which generates JSON request. Below is the code snippet of class along with test class. You can extend this as per your requirement

Apex class
public class JSONserialize{
//constructor
public JSONserialize(){
Contact con = new contact();
JSONSerialize.JSONinner handler = new JSONSerialize.JSONinner();// creating instance for JSONinner class
// Set additional field
    handler.name = 'JSONinner name';
    handler.type = 'Example';
    handler.c = new JSONserialize.contact1();// creating instance for contact1 object in JSONinner class
    handler.c.firstname= 'Type a'; 
    handler.c.lastname ='Smith';
    String jsonstring = Json.serialize(handler); //this method serializes the provided inputs
    System.debug('my output :::::::::::'+jsonstring); 
    System.assert(jsonstring.contains('Type a') == true);
    }
    // belpw are two inner classes to hold the variables needed in generating JSON request
public class JSONinner{
public string name{get;set;}
public string type{get;set;}
public contact1 c{get;set;}//the line here relates JSONinner class with contact1 class.. 
 }                           //That means i can access contact1 variables from JSONinner class

public class contact1{
public string firstname{set;get;}
public string lastname{set;get;}
}
}
Test Class
@istest
private class testJSONserialize{
    static testMethod void main(){
        JSONserialize o = new JSONserialize();
    }
}
Result
{
"type" : "Example",
"name" : "JSONinner name",
  "c" : {
       "lastname" : "Smith",
       "firstname" : "Type a"
   }
}

Friday, 27 June 2014

Radio Buttons Usage in Salesforce Passing only selected row values


 <apex:page controller="radioButtons" showHeader="false">  
 <Apex:form >  
 <script>  
 function myFunction( val){  
 var x = val.value;  
 callfunc(x);  
 }  
 </script>  
  <apex:pageBlock >  
  <apex:actionFunction name="callfunc" action="{!addaction}" reRender="text">  
  <apex:param value="" name="number"/>  
  </apex:actionFunction>  
 <apex:pageBlockTable value="{!rows}" var="aa">  
 <apex:column >  
  <apex:selectRadio value="{!SelectedValue}" onclick="myFunction(this);" >  
   <apex:selectOptions value="{!items}" />  
  </apex:selectRadio>  
 </apex:column>  
 </apex:pageBlockTable>  
  </apex:pageBlock>  
  <Apex:pageblock >  
  <font size="4">Result : <apex:outputText id="text" value="{!num}"> </apex:outputText></font>  
  </Apex:pageblock>  
 </Apex:form>  
 </apex:page>  
Apex Controller
 public class radioButtons {  
 public string SelectedValue{set;get;}  
 //integer to store the Result  
 public integer num{set;get;}  
 //list which stores the size of pageblock table to iterates radio buttons based on list size  
  public List<row> rows { get; set; }  
   //constructor  
   public radioButtons(){  
   num = 0;  
    rows = new List<Row>();  
    for(integer i=0;i<=4;i++){  
     rows.add(new row('5', '5'));  
     }  
   }  
   //method which adds the selected value to num integer  
   public void addaction(){  
   string number1 = system.currentPageReference().getParameters().get('number');  
   system.debug('Number::::::::::'+number1);  
   num = num+integer.valueof(number1);  
   }  
   //method which return the values and labels into apex select options  
    public List<SelectOption> getItems() {  
     List<SelectOption> options = new List<SelectOption>();  
     options.add(new SelectOption('5','5'));  
     options.add(new SelectOption('10','10'));  
     return options;  
   }  
   //inner class  
    public class Row {  
     public String Value { get; set; }  
     public String Label { get; set; }  
     public Boolean isChecked { get; set; }  
     public Row(String Value, String Label) {  
       this.Value = Value;  
       this.Label = Label;  
     }   
   }  
 }  
Screen Shot

Friday, 2 May 2014

Reports in vf page with iframe show blank page from Spring 14

With Spring '14, Salesforce has really picked up the pace when it comes to their Analytics. The Analytics API is now available in Apex. Salesforce has also added a new tag, <analytics:reportChart> for embedding report data into Visualforce pages. As of right now, there is only one Visualforce component available in the analytics namespace, but my guess would be that more will be coming.

Thursday, 13 March 2014

Trigger to Revert field to Old value.

Once working on a requirement i had a use-case like this :-
The user creates a product for example Pen with a cost of 500 and saves it, Now the user wants to update this price.
He can either increase the price or increase it.
If the user increases the price then it should be saved.
So my work to do was : - If the user gives a new price less than  first price then the record should be saved without any error messages and old price should reflect back to price field.

Let me explain in a diagrammatic way : - 
Price Increasing                                                             Price Decreasing
Initial price : - 500                                                       Initial price : - 500                    

New Price : - 600                                                      New Price:- 300

Price after saving :- 600.                                            Price after saving :- 500

Here is the Trigger Code :
 trigger trigbeforeupdate on member__c (before update) {  
    List<Member__c> toUpdate=new List<Member__c>();  
   for (Member__c member : trigger.new)  
   {  
     String newVal=member.Price__c;  
     String oldVal=trigger.oldMap.get(member.id).Price__c;  
      if (newVal < oldVal)  
     {  
       member.Text__c= oldVal;  
     }  
     else{  
      member.Text__c= newVal;  
      }  
   }  
 }  
-