Monday, 20 January 2014

Add/Remove Functionality in a VF page for Creating Multiple Records For a Particular Object.

Hi Guys
This is a very simple post. I had come across a scenario where I was asked to develop some functionality where user can create list of records at a time(clicking on save button on one time) and can remove row.
Here I have created a pageblock table and there I am displaying 5 rows to enter data and there column, Name , Phone and Action. In Action column Delete link is present.When that link(Delete) is clicked then particular row will be removed. Two button is there Add Row and Save.
Add Row-->  When that button is clicked one more row will be created in the pagablock table
Save--> It will save the record.

Here is the page

<apex:page controller="creatingListOfRecordsController">
    <apex:form >
    
        <apex:pageBlock title="Creating List Of Account Records">
        <apex:pageMessages></apex:pageMessages>
            <apex:pageBlockButtons location="top">
                <apex:commandButton value="Add Row" action="{!addRow}" reRender="table" immediate="true"/>
            </apex:pageBlockButtons>
                <apex:pageBlockTable value="{!accountwrapperList}" var="page" id="table"> 
                    <apex:column headerValue="Name">
                        <apex:inputField value="{!page.account.name}"/>
                    </apex:column>
                    <apex:column headerValue="Phone">
                        <apex:inputField value="{!page.account.Phone}" />
                    </apex:column>
                    <apex:column headerValue="Action">
                        <apex:commandLink value="Delete" action="{!removingRow}" immediate="true">
                            <apex:param name="index" value="{!page.counterWrap}"/>  
                        </apex:commandLink>
                    </apex:column>
                </apex:pageBlockTable>
                <apex:commandButton value="Save" action="{!saving}" />
            
        </apex:pageBlock>
    </apex:form>
</apex:page>

Here is the Controller

public with sharing class creatingListOfRecordsController {
    
    public list<Account> accountList{get;set;}
    public list<Accountwrapper> accountwrapperList{get;set;}
    public Integer counter{get;set;}
    
    public creatingListOfRecordsController(){
           counter = 0;
           accountList = new list<Account>(); 
           accountwrapperList = new list<Accountwrapper>();
           for(Integer i=0;i<5;i++){
               Accountwrapper actWrap = new Accountwrapper(new Account()); 
               counter++;
               actWrap.counterWrap = counter;
               accountwrapperList.add(actWrap); 
               
           }
       
    }
    
    public PageReference addRow(){
        //accountList.add(new Account());
        Accountwrapper actWrap = new Accountwrapper(new Account()); 
        
        counter++;
        actWrap.counterWrap = counter; 
        accountwrapperList.add(actWrap); 
        return null;    
    }
    public PageReference removingRow(){
    
        Integer param = Integer.valueOf(Apexpages.currentpage().getParameters().get('index'));
        
        for(Integer i=0;i<accountwrapperList.size();i++){
            if(accountwrapperList[i].counterWrap == param ){
                accountwrapperList.remove(i);     
            }
        }
        
        
        counter--;
        return null;    
    }
    
    public PageReference saving(){
        list<Account> updateAccountList;
        updateAccountList = new list<Account>();
        if(!accountwrapperList.isEmpty()){
            for(Accountwrapper accountWrapper:accountwrapperList){
                updateAccountList.add(accountWrapper.account);
            }
        }
        if(!updateAccountList.isEmpty()){
            upsert updateAccountList;
        }
       ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.Info,'Record Saved Successfully.');
       ApexPages.addMessage(myMsg); 
        return null;
    }
    
    public class Accountwrapper{
        public Account account{get;set;}
        public Integer counterWrap{get;set;}
        
        public Accountwrapper(Account act){
            this.account = act;  
             
        }
    }
    
}
The out put will be exactly like this image 


Saturday, 18 January 2014

Encryption and Decryption In Salesforce.

Encryption, is the process of changing information in such a way as to make it unreadable by anyone except those possessing special knowledge (usually referred to as a "key") that allows them to change the information back to its original, readable form.
To encrypt some value we have to use some key value that can be hard coded or we can generate key also by using this 

Blob cryptoKey = Crypto.generateAesKey(256);
We have to use same key to decrypt that value.

Here I am going to share some code.Hope it will help you. I have created one visualforce page and one controller. In the page only one field(Name) is there and two button(Save & Update).
When some value is entered in the name field and clicked on save button that value will be stored in the object encrypted format.
Now record id in the url and click on update button encrypted value will be converted in to original format.

Here is my page

<apex:page standardController="EnCrypt_Decrypt__c" extensions="EncryptExtension">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:inputField value="{!encrypt.Name}"/>
                <apex:commandButton value="Save" action="{!Save}"/>
                <apex:commandButton value="Update" action="{!test}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form> 
</apex:page>

Here is My Controller

public class EncryptExtension {
    public EnCrypt_Decrypt__c encrypt{get;set;}
    //Blob cryptoKey;
    Blob cryptoKey = Blob.valueOf('380db410e8b11fa9');
    public Id recordId{get;set;}
    public EncryptExtension(ApexPages.StandardController controller) {
        //cryptoKey = Crypto.generateAesKey(256);
        recordId = Apexpages.CurrentPage().getParameters().get('id');
        if(recordId !=null){
            encrypt = [SELECT id,Name From EnCrypt_Decrypt__c 
                    WHERE id=:recordId];
        }
        else{
            encrypt = new EnCrypt_Decrypt__c();
        }
    }
    
    public PageReference Save(){
         
         Blob data = Blob.valueOf(encrypt.Name);
         Blob encryptedData = Crypto.encryptWithManagedIV('AES128', cryptoKey , data );
         String b64Data = EncodingUtil.base64Encode(encryptedData);
         encrypt.name = b64Data ;
         
         insert encrypt;
         return null; 
    }
    public PageReference test(){
         
         //Blob cryptoKey = Crypto.generateAesKey(256);
         //Blob data = Blob.valueOf(encrypt.Name);
         Blob data = EncodingUtil.base64Decode(encrypt.Name);
         Blob decryptedData = Crypto.decryptWithManagedIV('AES128', cryptoKey , data);
         String dryptData = decryptedData.toString();
         System.debug('Printing dryptData '+dryptData);
         
         encrypt.name = dryptData;
         
         update encrypt;
         return null; 
    }
}

Thursday, 16 January 2014

Extend Feature Of Salesforce to Salesforce

Salesforce to Salesforce is a Force.com feature that lets you configure two Force.com environments (orgs) so that they share data records in real time. It is useful for those salesforce org who does business with partnership. While doing business It might required to share business data. if both org use salesforce then Salesforce to salesforce feature is easy to use for sharing data. 
As name suggest only this feature(S2S) only  used by Salesforce Org. 

How to use Salesforce to Salesforce ?

  • Enable salesforce to salesforce features in both the Org.(Source Org and Target org)
  • Create one Account and Contact in Source Org and provide email address(which is associated with target salesforce org. )
  • Now Create a Connection record from tab list. Choose Contact Name(which you have just created )
  • Send invitation 
  • Check mail, Activate connection
  • Choose object whose record you want to send and Save it 
  • Click on Edit link next to Object name in the Published Object section
  • Choose fields of chosen object
  • Now Come to target Org.
  • Click on Subscribe button in the Subscribe Object section 
  • Accept the object and map the field
  • Create some record in source org.
  • Go to the enhanced list view page 
  • Select the Record and click on Forward Connection button 
  • Choose the connection and send it
  • Check the status of record in the External sharing section (Which you have to add by editing layout from Related list Section) 
  • When status will be Active Sent then Record must be created in target Org.
This is default functionality of Salesforce to Salesforce(S2S).
Now somebody wants to do automatically data transfer. That means If some record is created in source org that record should be created automatically in target org if mapping is present.
For this requirement I have written a trigger and a class.

This is my trigger 

trigger InsertingAccountThroughS2S on Account(after insert) {
    
    Id networkId = ConnectionHelper.getConnectionId('Salesforce'); 
    list<Account> listOfAccounts = new list<Account>();
    list<PartnerNetworkRecordConnection> accountConnections =  new  list<PartnerNetworkRecordConnection>();
    
    for(Account act:trigger.new){
        
        if(act.ConnectionReceivedId == null){
        
            PartnerNetworkRecordConnection newConnection = 
                      new PartnerNetworkRecordConnection
                          ConnectionId = networkId, 
                          LocalRecordId = act.Id, 
                          SendClosedTasks = false, 
                          SendOpenTasks = false, 
                          SendEmails = false);
                          
             accountConnections.add(newConnection );
                          
              
        }
    }
    if (accountConnections.size() > 0 ) { 
          database.insert(accountConnections); 
    } 
   
}

This is the class

public class ConnectionHelper {
    public static Id getConnectionId(String connectionName) {
    
        List<PartnerNetworkConnection> partnerNetConList =
           [Select id from PartnerNetworkConnection where connectionStatus = 'Accepted' and connectionName =:connectionName];
        
        if ( partnerNetConList.size()!= 0 ) {
            return partnerNetConList.get(0).Id;
        }
        
        return null;
    }
}

Tuesday, 7 January 2014

Navigating to Standard Layout(Tab, Edit layout,List Layout) Using Action Global Variable

$Action is a global variable. A global merge field type to use when referencing standard Salesforce actions such as displaying the Accounts tab home page, creating new accounts, editing accounts, and deleting accounts.
Here I am sharing some visualforce code for the same.

<apex:page standardController="Account">

       //Navigating to new record page of Account
       <apex:outputLink value="{!URLFOR($Action.Account.New)}">
               Creating New Account
       </apex:outputLink>

      //Navigating to Account list View 
      <apex:outputLink value="{!URLFOR($Action.Account.List, $ObjectType.Account)}">
              Go to the Account List View
      </apex:outputLink>

      //Navigating to Account tab page
      <apex:outputLink value="{!URLFOR($Action.Account.Tab, $ObjectType.Account)}">
             Go to the Account tab
      </apex:outputLink>

      //Cloening Account Record 
      <apex:outputLink value="{!URLFOR($Action.Account.Clone, id)}">
             Cloning record
       </apex:outputLink>

       //id  means record id
      //Here we have to give accountid in url.
 
      //Editing Account Record
     <apex:outputLink value="{!URLFOR($Action.Account.Edit, id)}">
          Editing record
      </apex:outputLink>

      //Deleting Account Record
      <apex:outputLink value="{!URLFOR($Action.Account.Delete, id)}">
              Deleting Account Record
      </apex:outputLink>

     //submitting account record for approval 
     <apex:outputLink value="{!URLFOR($Action.Account.Submit for Approval, id)}">
           Submitting Record for Approval
     </apex:outputLink>
</apex:page>