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;  
      }  
   }  
 }  
-


Monday, 16 December 2013

Winter- 14 Maintenance Exam Test Questions

Options may vary in exam

So also refer Winter 14 release notes
Winter 14 Release notes
What is a capability of Collaborative Forecasts?

A. View the forecast separately for each product family
B. Reflect split revenue amounts in the forecast.
C. Display the forecast by territory when using territorry management
D. View the forecast for specific periods in a custom fiscval year.
Answers
A,B

What is a capability of embedded analytics?

A. Reports charts can be used to show data from tabular, summary and joined reports.
B. An embedded chart can be filtered to show data for the record on which it appears.
C. Report charts can be embedded on page layouts for standard and custom objects
D. An embedded chart can be used to share report data from a personnal folder
Answers
B,C

What is a capability of Salesforce Identity

A. Require users to have a HighAssurance session to edit, modify or delete selected objects
B. Require users to have a High Assurance session to access Reports, Dashboards, and connected Apps
C. Require users to use a time-based token when logging into Salesforce outside the trusted IP ranges.
D. Require users to enter a time-based token in addition to login credentials when accessing Salesforce
Answers
B,D

What is a capability of chatter Answers
Chosse 2 answers

A. Users can save drafts of questions an answers to be posted later.
B. Users can post private replies to an Idea on the Ideas tab
C.Users can reply to a question directly from an email notification
D. Users can view Questions and Ideas activity on Chatter profiles
Answers
C,D

How can an administrator customize Live Agent

A. Add images, animations, and custom agent
B. Add pre-recorded voice greetings and music to chat invitations.
C. Configure automated chat invitations to route chats to agents with specific skills
D. Configure agent settings to accept chats from the Q&A tab.
Answers
A,C

How can the Salesforce Console for Sales be customized?

A. Developpers can create custom console components to display sales information.
B. Sales reps can create personal customizations to override which tabs are subtabs.
C. Administrators can add custom buttons to the navigation tab and the highlights panel.
D. Administrators can define primary tabs and subtabs to show related records on one screen.
Answers
C,D

How can an administrator or developper restrict users from seeing other users in the organization?

A. Set the OWD for the User object to private
B. Enable the "Restrict Access to users" permission for all users
C. Disable manual sharing for the User object
D. Create a sharing rule to prevent users from seeing other users.
Answers
A

What is a capability of historical trending?

A. Hitorical trending reports can be filtered to show only records that have changed.
B. Hitorical trending can track number, formula and checkbox fields.
C. Hitorical trending reports show changed values in different colors
D. Hitorical trending can be enabled for all standard and custom objects.
Answers
A,C

What is a true statement regarding Salesforce Knowledge

A. Users can search and view articles without a knowledge User licence
B. Users can create and publish articles without the Manage Articles permission.
C. Users can provide feedback on the Chatter feed of a draft article.
D. Users can add and remove suppported languages in the knowledge base
Answers
A,C

What is a capability of Entitlement Management?

A. Create recurring milestone within an entitlement process.
B. Execute a flow when a milestone is met or violated.
C. Define criteria-based sharing rules for an entitlement process.
D.View the countdown tme to an activ milestone's Target Date.
Answers
A,D

How can an administrator customize Salesforce Console?

A. Add the Home tab to the navigation tab.
B. Add related lists to the Interaction log Layout.
C. Add the Most Recent Tabs component to the footer.
D. Add a dashboard component to the HighlightsPanel.
Answers
A,C

What is the capability of Site.com ?
Answers
A. Multilingual Language Support
B.HTML page imports are supported
C.Creating Preview oages, templates for different platforms using Live Mode

Thursday, 5 December 2013

Get fields of sobject in picklist of visualforce

 //Apex class  
 public string fields{set;get;}  
 Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();  
 //method for fields retrival and storage in picklist  
 public list<selectoption> getFields(){  
   String type='Account';  
   List<SelectOption> options = new List<SelectOption>();  
    //Creating sObject for dynamic selected object  
       Schema.SObjectType systemObjectType = gd.get(type);  
       //Fetching field results  
       Schema.DescribeSObjectResult r = systemObjectType.getDescribe();  
        Map<String, Schema.SObjectField> M = r.fields.getMap();  
       //Code for picklist of fields in  
       options.add(new SelectOption('None' ,'--None--')) ;  
       for(Schema.SObjectField fieldAPI : M.values()){  
       options.add(new SelectOption(fieldAPI.getDescribe().getName() ,       fieldAPI.getDescribe().getLabel())) ;  
       }  
       return options;  
     }//end of code for retrieving fields dynamically  
//vf page
 
  <apex:selectList value="{!Field}" size="1">  
    <apex:selectOptions value="{!Fields}">  
    </apex:selectOptions>  
  </apex:selectList>  

Thursday, 7 November 2013

PAGEBLOCKTABLE EDIT/DELETE FUNCTIONALITY

A basic example to edit/delete records individually.
Here i have taken two pages editdelete and editfun
on clicking edit in page 1 i am redirected to page 2 to edit the record and save it, after saving i am redirected to sobject detail page.
Below is code for page 1 :-

 <apex:page showHeader="false" sidebar="false" controller="editcon" tabStyle="Acc__c">  
 <apex:form >  
 <apex:sectionHeader title="edit/delete"/>  
 <apex:pageBlock >  
 <apex:pageBlockTable value="{!stun}" var="stu">  
 <apex:column >  
 <apex:param name="sid" value="{!stu.id}"/>  
 </apex:column>  
 <apex:column value="{!stu.name}"/>  
 <apex:column value="{!stu.Name__c}"/>  
 <apex:column value="{!stu.Age__c}"/>  
 <apex:column value="{!stu.Gender__c}"/>  
 <apex:column headerValue="Action">  
 <apex:commandLink value="EDIT" action="{!edit}">  
 <apex:param name="cid" value="{!stu.id}" assignTo="{!ecid}"/>  
 </apex:commandLink>  
 &nbsp;&nbsp;&nbsp;&nbsp;  
 <apex:commandLink value="DELETE" action="{!deletecon}">  
 <apex:param name="cid" value="{!stu.id}" assignTo="{!dcid}"/>  
 </apex:commandLink>  
 </apex:column>  
 </apex:pageBlockTable>  
 </apex:pageBlock>  
 </apex:form>   
 </apex:page>  
page 1 screen shot:-

controller class:-
 public class editcon {  
 list<Acc__c> stun = new list<Acc__c>();  
 list<Acc__c> stun1 = new list<Acc__c>();   
 public string ecid{get;set;}  
 public string dcid{get;set;}  
   public PageReference deletecon() {  
   stun1 =[Select Name, name__c, age__c from Acc__c where id=:dcid];  
     delete stun1;  
     pagereference pg= new pagereference('/apex/editdelete');  
     pg.setRedirect(True);      
     return pg;  
   }  
  public PageReference edit() {  
   pageReference pg = new pagereference('/apex/editfun?id='+ecid);  
   pg.setRedirect(false);  
     return pg;  
   }  
  public list<Acc__c> getStun() {  
   stun = [select name, name__c, age__c,gender__c from Acc__c];  
     return stun;  
   }  
 }  
}


page  2:-
 <apex:page showHeader="false" sidebar="false" standardController="Acc__c"tabstyle="Acc__c">  
 <apex:form >  
 <apex:sectionHeader title="Edit the record"/>  
 <apex:pageBlock tabStyle="Acc__c">  
 <apex:pageBlockButtons location="both">  
 <apex:commandButton value="save" action="{!save}"/>  
 </apex:pageBlockButtons>  
 <apex:pageBlockSection >  
 <apex:inputField value="{!Acc__c.Name__c}"/>  
 <apex:inputField value="{!Acc__c.Age__c}"/>  
 </apex:pageBlockSection>  
 </apex:pageBlock>  
 </apex:form>  
 </apex:page>  
screen shot of page 2:-

Monday, 4 November 2013

Example to Display Page block Table on button click

<apex:page controller="showpgbtable" >
 <apex:form >
  <apex:commandButton value="showtable" action="{!accountlist}" reRender="panel"/>
   <apex:outputPanel id="panel" >
    <apex:pageBlock rendered="{!rendered}" >
     <apex:pageBlockTable value="{!accounts}" var="a" >
      <apex:column value="{!a.name}"/>
     </apex:pageBlockTable>
    </apex:pageBlock>
   </apex:outputPanel>
 </apex:form>
</apex:page>

//controller class
public class showpgbtable {
 public list<Account> acc1 = new list<account>();
public Boolean rendered{set;get;}
public showpgbtable(){ //constructor
rendered =false;
}
 public pageReference Accountlist(){
    acc1 = [select id,name from account ];
     rendered  = true;
    return null;
   }
   public list<account> getaccounts(){
   return acc1;
   }
Screen Shots:-

}

Sunday, 3 November 2013

UPLOADING IMAGE IN SALESFORCE THROUGH VF PAGE

A very common requirement we come across is uploading image/photo through vf pages. While doing this task we need to keep in mind that we can't directly display image in visualforce page in salesforce. It should be stored at some place- There are 3 places where we can store our images

  1. Documents
  2. Static Resources
  3. Attachments.
Below i am illustrating an example of uploading and displaying image in visualforce using Documents sobject.


<!--vf page code-->
 <apex:pageBlockSection title="Upload Photo" collapsible="false" columns="1" >  
 <apex:image url="https://c.ap1.content.force.com/servlet/servlet.FileDownload?file={!doc}" height="100"       width="100" rendered="{!showimage}" /> /*contains the url of documents,{!doc} gives the image dynamically */  
  <apex:inputFile value="{!Document.body}" filename="{!document.name}" />  
 <center><apex:commandButton value="Upload" action="{!save}" /></center>  
  </apex:pageBlockSection>  
//apex class code
 public boolean showimage{set;get;}  
  public final document t;  
   private ApexPages.StandardController stdcontroller;  
   public getdocumentid(ApexPages.StandardController stdcontroller) {  
   t = (Document) stdcontroller.getRecord();  
     t.folderid = UserInfo.getUserId(); //this saves record in My Personal Documents  
     this.stdcontroller=stdcontroller;  
     }    
  public pagereference save(){  
   this.stdcontroller.save();// this method implements the standard save method.  
   pagereference pg=new pagereference('/apex/vfpageimageupload');  
   showimage=true;  
   return pg;  
   }   
   List<document> d;  
   public id doc{set;}  
   public id getdoc()  
   {  
   d=[select id from document order by id desc limit 1]; //gets id of document inserted last in sobject  
   return d[0].id;// returns id value of list d  
   }