Tag Archives: Salesforce

Populate Picklist from Custom Object to the Visualforce Page

Controller:

public with sharing class Sample
{
    public string selectedValue {get; set;}
    public List<SelectOption> industry {get; set;}
    
    public void getIndustry()
    {
        Schema.DescribeFieldResult industryDescription = Account.Industry.getDescribe();
        industry = new List<SelectOption>();
        
        for (Schema.Picklistentry pl : industryDescription.getPicklistValues())
        {
            industry.add(new SelectOption(pl.getValue(),pl.getLabel()));
        }
    }
    
    public void checkValue()
    {
        System.debug('Selected Industry Type - ' + selectedValue);
    }
}

Visualforce Page:

<apex:page controller="Sample" action="{!getIndustry}" sidebar="false" showHeader="false">
    <apex:form >
        <apex:pageblock>
            <apex:pageBlockSection columns="1" >
                <apex:outputLabel value="Industry Type" />
                <apex:selectList size="1" value="{!SelectedValue}" >
                    <apex:selectOptions value="{!industry}"/>
                    <apex:actionSupport event="onchange" action="{!checkValue}" />
                </apex:selectList>
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>

Output:

Difference Between Clone and DeepClone in Apex in Salesforce

Clone Deep Clone
Generally clone the list of object and keep the reference. Generally it clone the list of object but don’t hold any reference.
A Clone doesn’t keep the Ids. A Deep Clone keeps the Id.
Supports primitive data type. Doesn’t support primitive datatype.
Parameters are not applicable. Parameter are applicable.

Here is a an example to understand difference between Clone and DeepClone:
I am creating a New Account with some fields.

Account acc = new account(Name = 'Salesforce', Billingcity = 'San Francisco', Type = 'Customer - Direct', Phone = '9999999999');
insert acc;

This creates a record in the Account as shown below:

Now, I am cloning it and inserting again.

Account acc = new account(Name = 'Salesforce', Billingcity = 'San Francisco', Type = 'Customer - Direct', Phone = '9999999999');
insert acc;

//Cloning the above Account Record acc
Account accCloneCopy  = acc.clone(false, false, false, false);
insert accCloneCopy;

It creates a new copy of the record with same values, since it keeps the reference, new record ID is generated for cloned record.

Now, when I try to deepclone the record: (Deepclone is done by keeping true in the parameters) like,
clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber)

Account acc = new account(Name = 'Salesforce', Billingcity = 'San Francisco', Type = 'Customer - Direct', Phone = '9999999999');
insert acc;

//Deep cloning the above record
Account accDeepCloneCopy  = acc.clone(true, true, false, false);
insert accDeepCloneCopy;

It shows an error, because the Id is also considered and cannot insert the deppcloned record:

Test Class for Batch Apex in Salesforce

Batch Class:

global class BatchAccount implements Database.Batchable<sObject> 
{
    global Database.QueryLocator start(Database.BatchableContext BC) {
		
        return Database.getQueryLocator('SELECT Id,Name FROM Account');
    }
	
    global void execute(Database.BatchableContext BC, List<Account> scope) {
		
        for(Account a : scope)
        {
            a.Name = a.Name + ' Updated';
        }
        update scope;
    }
	
    global void finish(Database.BatchableContext BC) {
		
    }
}

Test Class:

@isTest 
public class BatchAccountTest 
{
    static testMethod void test() 
    {
        List<Account> accList = new List<Account>();
        for(Integer i = 0 ; i < 200; i++)
        {
            Account acc = new Account();
            acc.Name = 'Name' + i;
            accList.add(acc);
        }
        Insert accList;
        
		Test.startTest();
		BatchAccount obj = new BatchAccount();
		DataBase.executeBatch(obj); 
		Test.stopTest();
		
		//Verify accounts updated
		List<Account> accUpdatedList = [SELECT Id, Name FROM Account];
		System.assert(accUpdatedList[0].Name.Contains('Updated'));
    }
}

Select All Checkbox Using Javascript in Visualforce Page

Controller:

public with sharing class Sample { 

    public List<AccountWrapper> accountWrapperList {get; set;}
    
    public Sample (){
        if(accountWrapperList == null) {
            accountWrapperList = new List<AccountWrapper>();
            for(Account a: [SELECT Id, Name From Account Limit 10]) {
                accountWrapperList.add(new AccountWrapper(a));
            }
        }
    }
     
    public class AccountWrapper {
        public Account acc {get; set;}
        public Boolean isSelected{get; set;}
 
        public AccountWrapper(Account a) {
            acc = a;
            isSelected = false;
        }
    }  
    
}

Visualforce Page:

<apex:page controller="Sample" sidebar="false" showHeader="false">
    <script type="text/javascript">
        function selectAllCheckboxes(obj,InputID){
            var inputCheckBox = document.getElementsByTagName("input");    
            for(var i=0; i<inputCheckBox.length; i++){          
                if(inputCheckBox[i].id.indexOf(InputID)!=-1){                                     
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockTable value="{!accountWrapperList}" var="a" id="table" title="All Accounts">
                <apex:column >
                    <apex:facet name="header">
                        <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                    </apex:facet>
                    <apex:inputCheckbox value="{!a.isSelected}" id="inputId"/>
                </apex:column>
                <apex:column value="{!a.acc.Name}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:

Salesforce Apex Sharing Reason

Apex sharing reason is used to identify, why the record are shared with the user. If a developer is doing any operation on that record sharing then he can able to identify, in which sharing records he needs to do the operation. Its especially for managing a record sharing through apex code. We can share a record multiple times with the same user or group using different Apex sharing reasons.

Lets go through this with below example.

Here I’ve a custom object “Bank” and the OWD of this object is set as “private” under the “Security control” for users.

If an object OWD is set as “private”, then user have access to the object records which is created by himself. Once you made this change “Sharing” button will be added into the “Bank” page layout. By using this Sharing button you can able to view the record access which means who have access to that records.

But here I will explain you how to extend the records access(Sharing the record) to users or group through apex code.

Here for “Bank” custom object the OWD is set as “private” under the “Security control” for users.

In “Bank” custom object in Apex Sharing Reason related list, I’ve created an Apex Sharing Reason as “Account Manager”.

In my org I have a user called Abhijeet. He is the Account Manager. If any Bank record is created by an user then that record should shared using apex with the Account Manager Abhijeet. Suppose Biswajeet is creating a Bank record called “State Bank of India” then that record should be shared with Abhijeet.

Here is the “State Bank of India” record, and record owner is Biswajeet.

Using below apex code we can share this record with Abhijeet. In below apex code “UserOrGroupId” is Abhijeet UserId and “ParentId” is “State Bank of India” record Id.

Bank__Share objBank = new Bank__Share();
objBank.AccessLevel = 'Edit'; //Access Level
objBank.UserOrGroupId = '00590000002Qi1f';//UserId or Public Group Id
objBank.ParentID = 'a0B9000000yNgXo';//Object Record Id
objBank.RowCause = Schema.Bank__Share.RowCause.Account_Manager__c;//Record Sharing Reason
Insert objBank;

Salesforce displays Apex sharing reasons in the Reason column when viewing the sharing for a custom object record in the user interface. This allows users and administrators to understand the purpose of the sharing. After executing above apex code the output will look like below snap.

Note:

  • Only users with the “Modify All Data” permission can add, edit, or delete sharing that uses an Apex sharing reason.
  • Deleting an Apex sharing reason will delete all sharing on the object that uses the reason.
  • You can create up to 10 Apex sharing reasons per custom object.
  • You can create Apex sharing reasons using the Metadata API.