Thursday 28 April 2016

SFDC USEFUL CODING CONCEPTS

Bulkification Example: Let’s analyze the governor limit for DML statements.
This code is not bulkified and will go over the 150 DML statements limit:
// Remember that up to 200 records can be in Trigger.new
for (Opportunityopp : Trigger.new) {
Taskt   = new Task();
t.Name   = 'Give your prospect a free t-shirt';
t.WhatId = opp.Id;
insertt// You'll get an error after the 150th opp!
}
This code is bulkified and will not hit any governor limits. It uses Lists and will only do one DML statement no matter how many records are in the trigger:
// Do an insert DML on all tasks at once using a List
List<Task>taskList = new List<Task>();
for (Opportunityopp : Trigger.new) {
Taskt   = new Task();
t.Name   = 'Give your prospect a free t-shirt';
t.WhatId = opp.Id;
taskList.add(t);
}
inserttaskList// Notice this is outside the loop













Wrapper Class | Wrapper Class Example
Wrapper Class
Wrapper class is a class whose instances are collection of other objects. It is used to display different objects on a Visual Force page in same table.
Wrapper Class Example 
Wrapper class for displaying Checkbox and String Data types in single table
Create a Class with the name “WrapperIntStringDisplayClass ” :
public with sharing class WrapperIntStringDisplayClass {
// Creating lists for the object Testing__c and DataLoadTest__c.
List<Testing__c>lsttest = new List<Testing__c>();
List<DataLoadTest__c>lstdlt = new List<DataLoadTest__c>();
// Creating List for Wrapper class
public List<wrapper>lstw = new List<wrapper>();
// Get method calling from PageBlockTable and return the list of wrapper to Table
public List<wrapper>getLstwrapperIntString() {
lsttest = [select name,city__c from Testing__c];
lstdlt = [select country__c,phone__c from DataLoadTest__c];
for(Integer i=0;i<lstdlt.size();i++){
lstw.add(new wrapper(lsttest[i].name,lsttest[i].city__c,lstdlt[i].country__c,lstdlt[i].phone__c));
}
returnlstw;
}
// Wrapper Class Construction
public class wrapper{
public String Tname{get;set;}
public String Tcity{get;set;}
public String Dcountry{get;set;}
public String Dphone{get;set;}
// Wrapper class constructor
public wrapper(String Tname,StringTcity,StringDcountry,StringDphone){
this.Tname=Tname;
this.Tcity=Tcity;
this.Dcountry=Dcountry;
this.Dphone=Dphone;
}
}
}
Create a VF Page with controller:
<!– Creating this page for dispalyTesting__c and DataLoadTesting__c object in single table with check box –>
<apex:page sidebar=”false” controller=”WrapperIntStringDisplayClass”>
<apex:form>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockTable value=”{!lstwrapperIntString}”             var=”w”>
<apex:columnheadervalue=”Action”>
<apex:inputcheckbox />
</apex:column>
<apex:columnheadervalue=”TestingName”>
{!w.Tname}
</apex:column>
<apex:columnheaderValue=”TestingCity”>
{!w.Tcity}
</apex:column>
<apex:columnheadervalue=”DataLoadCountry”>
{!w.Dcountry}
</apex:column>
<apex:columnheaderValue=”DataLoadPhone”>
{!w.Dphone}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>



Wrapper Class Example  2



Wrapper Class

UPDATED March 2013
In the Visualforce community boards one of the most commonly asked questions is, "How can I display a table of records with a check box and then process only the records that are selected?", like this:
https://s3.amazonaws.com/dfc-wiki/en/images/f/fe/Wrapper_class.png
https://d2hwpln2xvs3s.cloudfront.net/skins/common/images/magnify-clip.png
Wrapper class example
This is a perfect scenario where a wrapper class can be used. Most of my instructions and comments are in the code but anyone should feel free to modify this entry to make it easier to understand.
First the Controller:
01
public class wrapperClassController {
02


03
    //Our collection of the class/wrapper objects cContact
04
    public List<cContact> contactList {get; set;}

05

06
    //This method uses a simple SOQL query to return a List of Contacts

07
    public List<cContact> getContacts() {
08
        if(contactList == null) {

09
            contactList = new List<cContact>();
10
            for(Contact c: [select Id, Name, Email, Phone from Contact limit 10]) {

11
                // As each contact is processed we create a new cContact object and add it to the contactList
12
                contactList.add(new cContact(c));

13
            }
14
        }

15
        return contactList;
16
    }

17

18


19
    public PageReferenceprocessSelected() {
20


21
                //We create a new list of Contacts that we be populated only with Contacts if they are selected
22
        List<Contact> selectedContacts = new List<Contact>();

23

24
        //We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list

25
        for(cContactcCon: getContacts()) {
26
            if(cCon.selected == true) {

27
                selectedContacts.add(cCon.con);
28
            }

29
        }
30


31
        // Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc
32
        System.debug('These are the selected Contacts...');

33
        for(Contact con: selectedContacts) {
34
            system.debug(con);

35
        }
36
        contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now

37
        return null;
38
    }

39

40


41
    // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
42
    public class cContact {

43
        public Contact con {get; set;}
44
        public Boolean selected {get; set;}

45

46
        //This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false

47
        public cContact(Contact c) {
48
            con = c;

49
            selected = false;
50
        }

51
    }
52
}
And then the Page:
01
<apex:page controller="wrapperClassController">
02
    <apex:form >

03
        <apex:pageBlock >
04
            <apex:pageBlockButtons >

05
                <apex:commandButton value="Process Selected" action="{!processSelected}"rerender="table"/>
06
            </apex:pageBlockButtons>

07
            <!-- In our table we are displaying the cContact records -->
08
            <apex:pageBlockTable value="{!contacts}" var="c" id="table">

09
                <apex:column >
10
                    <!-- This is our selected Boolean property in our wrapper class -->

11
                    <apex:inputCheckbox value="{!c.selected}"/>
12
                </apex:column>

13
                <!-- This is how we access the contact values within our cContact container/wrapper -->
14
                <apex:column value="{!c.con.Name}" />

15
                <apex:column value="{!c.con.Email}" />
16
                <apex:column value="{!c.con.Phone}" />

17
            </apex:pageBlockTable>
18
        </apex:pageBlock>

19
    </apex:form>
20
</apex:page>

Wraperclass 2 example


Deepak Anand
Let me put ma 2 cents.....Say you have to create a Table in your Visualforce Page in other words a PageBlockTable(apex:pageBlockTable). Each row of the table is suppose to show information from a Contact record also some details from the related Account record too. So, it would be nice, it we had a Class(An Abstract Data Type or a wrapper or a kind of a temporary holder for information) where it could hold the details for each row from different tables:

public class TableRow{
        public String Name      {get;set;}
        public String Phone     {get;set;}
        public String Company   {get;set;}
}

Now, your Apex Controller class will have this:

public class WrapperDemoController{
    /*Our Wrapper Class*/
    public class TableRow{
        public String Name      {get;set;}
        public String Phone     {get;set;}
        public String Company   {get;set;}
    }
  
    /*Public Property that will hold all the TableRows and our PageBlockTable can use this Variable   to get the whole List of rows*/
    public List<TableRow>RowList {get; set;}

    /*Constructor that runs a SOQL to get all the Records and build the List. This get executed automatically on the Page Load.*/
    public WrapperDemoController(){

        RowList = new List<TableRow>();
        TableRowtr;

        /*Building the List of TableRows*/
        /*Fetch all the Contacts and then build the List*/
        for(Contact con : [SELECT Name, Phone, Account.NameFROM Contact]){

            tr = new TableRow();
            tr.Name = con.Name;
            tr.Phone = con.Phone;
            tr.Company = con.Account.Name;

            /*Add the TableRow to the List then and there*/
            RowList.add(tr);
        }
    }
}

Now the Visualforce Markup will be:

<apex:pagecontroller="WrapperDemoController">
    <apex:pageBlock>
        <apex:pageBlockTablevalue="{!RowList}" var="row">
            <apex:columnvalue="{!row.Name}"/>
            <apex:columnvalue="{!row.Phone}"/>
            <apex:columnvalue="{!row.Company}"/>
        </apex:pageBlockTable>  
    </apex:pageBlock>
</apex:page>

So, in simpler words wrapper could be thought of as temporary holder/buffer for information lying across different tables queried via a SOQL.

Custom Settings:

Change your trigger on the fly using Custom Settings

MARCH 2, 2014
Preface: this post is part of the Advanced Apex Concepts series.
Custom Settings are a hidden gem in Apex that always impresses people, especially bosses!
Custom Settings are variables that you use in your code but set and modify outside of your code.
Here’s an example:
You’re writing a trigger that sets a “Customer Service Rep” field on an Account every time there’s a high value Opportunity associated with it. Two things are certain: (1) The CSR on duty changes every week and (2) the threshold for a “high value” opp changes often since your company is expanding.
A perfect use case to use Custom Settings to set the CSR on duty and the “high value” opp threshold!
Benefits of using Custom Settings:
  • Change your variables through Salesforce.com without deploying code!
  • Any non-coder admin can now modify your variables and change how your code works!
  • Show your boss that you’re thinking ahead and not just concerned with doing the bare minimum!
Step 1: Create a Custom Setting “object” for your trigger:
Setup >> Develop >> Custom Settings >> New
http://www.sfdc99.com/wp-content/uploads/2014/03/create-custom-setting2.png
Step 2: In your Custom Setting object, create Custom Fields for each needed variable:
http://www.sfdc99.com/wp-content/uploads/2014/03/custom-setting-fields.png
Step 3: Create a Custom Setting record and edit its variables
Navigate to your Custom Setting >> Manage >> New
http://www.sfdc99.com/wp-content/uploads/2014/03/custom-setting-record.png
Step 4: Use your Custom Setting in your code!
triggerAddCSR on Opportunity (before insert) {
// Grab your Custom Setting values
CSR_Settings__csettings = CSR_Settings__c.getInstance('csr');
StringCSR_USER_ID      = settings.CSR_User_ID__c;
DecimalOPP_MIN_VALUE    = settings.Opp_Minimum_Value__c;
 
// Create a master list of accounts to bulk update
List<Account>accounts = new List<Account>();
 
for (Opportunityopp : Trigger.new) {
// Make sure we meet the minimum threshold
if (opp.Amount>= OPP_MIN_VALUE) {
// This is a trick to get the related account!
Accountacc = new Account();
acc.Id      = opp.AccountId;
 
// Update the CSR and add to master list
acc.CSR__c  =CSR_USER_ID;
accounts.add(acc);
    }
  }
// Update the master list of accounts
updateaccounts;
}
Now if you need to edit the CSR on duty or the minimum Opportunity amount threshold, simply edit the record in Step 3 – no rewriting or deploying code necessary!
One important note – custom Settings aren’t automatically transferred between sandboxes and production, so make sure you include them in both places or your code will break!


Custom Settings 2 example

The Wonders of Salesforce Custom Settings

http://makepositive.com/newsite/wp-content/themes/makepositive/images/icon-date.png  July 29, 2014     http://makepositive.com/newsite/wp-content/themes/makepositive/images/icon-avatar.png  Ali Zafar
Salesforce first introduced Custom Settings back in 2009 and since then rarely is there an AppExchange package or solution that does not use them in some form. However, in our client engagements we come across many customers who are still to realize the benefits and have worked around them to date. In this blog our London based Salesforce consultant Ali Zafar explains what they are, the reasons for using them, and how they can be used to improve your change management processes and deployment…
David Liu explains Custom Settings very succinctly on his sfdc99.com blog as “Custom Settings are variables that you use in your code but set and modify outside of your code.” Using Custom Settings appropriately can save you on programmer and CRM admin user’s time.
Custom settings are very useful when it comes to storing static or reusable information in Salesforce, plus it also can work as a switch to turn your application rules ON and OFF. For both Admins and Developers, Custom Settings act as a golden child in the Salesforce family. Under the hood Custom Settings are much like Custom Objects and are accessible via their own API, but you can’t have triggers on a Custom Setting and the available field types are more limited. They do count towards your Custom Objects governor limit however.
There are two types of settings – List and Hierarchical. In this post we are going to look at each of them and suggest typical ways in which you can use them.
List Custom Settings
List settings are structured similar to records held in a custom object. They allow you to store org-wide static data that is frequently used, and therefore cached for performance. Data in List settings do not vary by user and profile, there is no ownership, field level security or record security, and it is available organisation wide (i.e. public for all). It’s best used for data lists, especially reference code lists, and great for when you want to convert code values from one system to another or any other mapping or list.

You may ask why we need to use List settings when same thing can be done through a Custom Object? Well the answer is simple. Custom Settings are stored in the application cache and do not count against SOQL limits when fetched. Also they are much quicker to implement, easier to maintain and they won’t use up one of your precious Custom Tab limits to maintain. They can also only be updated by a System Administrator (or Configure Application profile permission user). Custom Settings have their own methods to access them – we will have a look below at an example on how we can use getInstance() and getAll() methods.
Lets consider a scenario where your customer Service team wants to differentiate between incoming email address with domain names. They want their partner emails to be redirected to different queue with some additional business logic to be applied. For creating a new Custom Settings go to Setup – Develop – Custom Settings, Click New and enter details.
pic-1
Once you have created the custom setting, you need to define the fields to add to it. The following are the data types that are available for custom settings fields.
Salesforce custom settings
In the image below we are storing a few email domain names in custom settings and later fetching them via Apex using getInstance() and getAll() methods. The purpose of this list is to allow us to select the correct Partner details based on company’s domain name. By using the custom setting we can quickly find the mappings we need without querying for a matching field on the Account record (where we may have millions of records).
custom settings
The following code snippet is an example of one of the ways to use List custom settings in Apex:
Custom settings Salesforce
In addition to holding lists of static data, List Custom Settings are also useful for:
·         Holding environment credentials: Webservice endpoints for production, uat, prepod and dev are likely to be different – don’t hardcode them!
·         To hold environment ids: If you have rules, buttons or links that need to utilize specific Salesforce Id values these are going to be different across your environments or may change over time. Rather than hard coding a user or profile id in a Rule, Formula or Apex code you can use a custom setting to hold values such as an ‘Escalation User Id’.
·         To hold environment values: You may have rules about opportunities greater than $100k however this limit make change in the future dur to changes in market conditions. Hold the value in a List custom setting if it applies globally to all users (without question) and you need to reference it in Apex. Hold it in a Hierarchical setting if there’s a chance you need to switch it off by user or profile or have different values, or if you need to access the value in a Workflow, Formula Field or Validation Rule.
Custom Settings as a Switch
on / offf
Hierarchical Custom Settings are defined once and can hold a unique set of values for the Organisation, each Profile or each individual User. Salesforce automatically grabs the lowest level of setting for the running user when a getInstance() call is made, or when accessed in a configuration such as a Validation Rule, Workflow or Formula Field. Note that only Hierarchical settings can be accessed declaratively whereas List settings are for Apex/Visualforce only.
Using hierarchical settings can provide the functionality of a switch, which you can use as ON or OFF to disable Integrations, Triggers, Workflow Rules, Assignment Rules and Validation Rules for all users, specific profiles or individual users. This is possible when you use hierarchical custom settings with a checkbox field to control your system functions, but you could also use it to control internal debugging log levels for example.
Using hierarchical settings lets you control down to an individual user for whom it is de-activated, so you can force a data validation rule for some users and disable it for others. For triggers it is even more useful because triggers cannot be de-activated in a production org without carrying out time consuming deployments (once to switch off and then to switch on again), with no guarantee of how long each deployment will take (depending on the instance queues, org usage and number of unit tests in the org to be run each time).
This becomes especially useful when performing data fixes or data migration, or if needing to disable a failing trigger or Apex functionality in a live org (saving hours in performing the redeployments). Because of the hierarchical nature you can isolate to an individual user, so you could disable all triggers firing during a Data Load for an Admin user to drastically reduce the time to upload data or for an Admin when fixing data errors to switch off emails being sent to customers from Workflows. No more need to deactivate rules one by one and re-activate them when you’ve finished, and work no longer has to always be performed ‘out-of-hours’.
Below is an example of how a hierarchal custom setting can be implemented. You can add new records as Profiles or individual Users to bypass any Apex Triggers or Validation Rules.
In this example we create a validation rule to prevent a User from closing a case with any Open activities, and use $Setup.Your_Custom_Setting with an AND condition in our validation rule to switch this off centrally:
AND
(
ISPICKVAL( Status , “Closed”) ,
ISCHANGED( Status ) ,
Open_Activities__c<> 0 ,
$Setup.MP_Global_Settings__c.Fire_Validation_Rules__c
)
As you can see if you built all your validation rules, workflow rules and triggers using this technique it is an extremely powerful way of controlling behaviour across the entire application.
You can set the default Organisation Level value (as seen in image below) to fire all Validation, Workflow, Assignment and Triggers rules for all Users. To bypass any profile or user, add a record in Custom settings. In the example below only triggers will fire for System Administrator Profile and no rules will fire for User Ali Zafar, even though he is a System Administrator because the lowest level of custom setting is applied automatically. Also, note that the user personal settings will override all his other settings.
Salesforce settings
This technique can be expanded upon for a number of other reasons:
·         To switch application functionality on/off: Useful for orgs with multiple divisions who want different behaviours. Try to create re-usable settings by function such as ‘Reassign Old Leads to Queues’ rather than generic divisional settings such as ‘Run Marketing Rules’.
·         To control change management: Similar to the above, when implementing a suite of changes where you need to be able to ‘rollback’ the function in the event of an issue, or you wish to soft launch a feature, consider implementing a Hierarchical custom setting to let you test the change in production for a single user or profile before releasing to all users.
·         To provide dynamic page overrides: Different Visualforce or standard pages can be called in a Button or Apex Visualforce Controller based on the Custom Settings for a particular profile or user. This can even be used to include different logos or branding.
·         To extend the Profile with custom attributes: Profiles cannot currently be extended with custom fields, so use a Hierarchical Custom Setting to define the fields you need to add at a Profile level. For example, a Sales Commission % field which is used in a formula field. This can then be further overridden by individual user and potentially saving on Profile proliferation!
·         To switch Visualforce components on/off: Users can hide sections on Page Layouts but they can’t hide sections on a Visualforce page (ok they can collapse the section but it isn’t remembered between sessions). You can create “Show Financials”, “Show KPIs”, “Show Case History” checkbox options to switch this data off on Visualforce pages using the Rendered attribute to control visibility. Useful when you don’t want to hide the data completely through Field Level Security, just simplify the pages, and very useful for showing different features to Community users by Profile or User and even saving results by user to collapse or hide sections.
Hopefully this blog has inspired you to consider using custom settings more, and you have a better understanding of the different types of custom setting and when each is appropriate. There are some gotchas, but let’s leave those to the next blog…
If you have any questions or want to speak to specialised Salesforce consultantsabout your upcoming projects, get in touch today.




est Answer chosen by Admin  
You can do it in two ways - Put the Age value from javascript into an inputHidden apex tag that has a value from your controller, or add an apex param tag onto your actionFunction:

Using an inputHidden:
<script> Age = CDateArr[3] - BDateArr[3]; document.getElementById('{!$Component.ageop}').value = Age; </script><apex:inputHidden id="ageop" value="{!ageVal}"> Apex: public String ageVal {get; set;}

Using an actionFunction:


<script> Age = CDateArr[3] - BDateArr[3]; agesend(Age); </script><apex:actionFunction name="agesend" action="{!doAction}"><apex:param name="age" value="0" assignTo="{!ageVal}" /></apex:actionFunction> Apex: public String ageVal {get; set;} public void doAction() { // Do something here if required }



Using an actionFunction would be more beneficial if you wanted to run an action (It looks as if you don't need to)
·         June 23, 2009
·         ·
·         Like
·         0
·         ·
·         Dislike
·         0




To pass parameters from the Visualforce page to the controller, you can use the <apex:param> as demonstrated on this sample... 
1.  <apex:pagecontroller="aaPage52">
2.  <apex:formid="RID">
3.  <apex:commandButtonvalue="click"action="{!TestX}"rerender="RID">
4.  <apex:paramname="X"value="{!X + 1}"/>
5.  </apex:commandButton>
6.  <apex:outputTextvalue="{!X}"/><br/>
7.   
8.  <apex:commandButtonvalue="click"action="{!TestX2}"rerender="RID">
9.  <apex:paramassignTo="{!X2}"value="{!X2 + 1}"/>
10. </apex:commandButton>
11. <apex:outputTextvalue="{!X2}"/><br/>
12.  
13. </apex:form>
14. </apex:page>
1.  publicclass aaPage52 {
2.  publicInteger X {get;set;}
3.  publicInteger X2 {get;set;}
4.   
5.  public aaPage52(){
6.          X =0;
7.          X2 =0;
8.  }
9.  publicPageReferenceTestX(){
10. StringstrX=ApexPages.currentPage().getParameters().get('X');
11. if(strX!=null){
12. this.X=Integer.ValueOf(strX);
13. }
14. returnnull;
15. }
16. publicPageReferenceTestX2(){
17. returnnull;
18. }
19. }

Custom settings

From sfdcpoint.com

Custom Setting in Salesforce

Custom settings are similar to custom objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. All custom settings data is exposed in the application cache, which enables efficient access without the cost of repeated queries to the database.
We can create custom setting for storing data similar to custom objects in salesforce but here the data is static.
Similar to custom object, we can create fields in custom setting and after creating the fields, we can click on ‘Manage’ button to add records in that custom setting. Then we can use the values in these records in our apex code, validation rules. The benefit of using custom setting instead of custom objects:
·         Data in custom setting is available in application cache, hence efficient and fast access.
·         No need to waste SOQL for fetching data from custom setting. There are some methods available in custom settings that we can use to get the data instead of SOQL.
Types of custom settings available in salesforce :
List Custom Settings:
A type of custom setting that provides a reusable set of static data that can be accessed across your organization. If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it. Data in list settings does not vary with profile or user, but is available organization-wide. Examples of list data include two-letter state abbreviations, international dialing prefixes, and catalog numbers for products. Because the data is cached, access is low-cost and efficient: you don’t have to use SOQL queries that count against your governor limits.
heirarchy 2
Hierarchy Custom Settings:
A type of custom setting that uses a built-in hierarchical logic that lets you “personalize” settings for specific profiles or users. The hierarchy logic checks the organization, profile, and user settings for the current user and returns the most specific, or “lowest,” value. In the hierarchy, settings for an organization are overridden by profile settings, which, in turn, are overridden by user settings.
Hierarchy
In above screenshot, you can see that records in a particular custom setting can be created for particular profile or user. But this is not the case with List custom setting. Records in list custom setting are available for all users and profile in application.
Salesforce imposes certain limits on the amount of cached data and on custom settings:
·         The total amount of cached data allowed for your organization is the lesser of these two values:
o    10 MB
o    1 MB multiplied by the number of full-featured user licenses in your organization
For example, if your organization has three full licenses, you have 3 MB of custom setting storage. If your organization has 20 full licenses, you have 10 MB of storage.
Each Certified managed package gets its own separate limit in addition to your organization limit. For example, if your organization has two certified managed packages installed and your organization has three full licenses, each certified managed package can have 3 MB of custom setting storage, in addition to your organization’s 3 MB custom setting storage limit.
·         300 fields per custom setting.
·         You can’t share a custom setting object or record.
·         No owner is assigned when a custom setting is created, so the owner can’t be changed.
·         Custom settings are a type of custom object. Each custom setting counts against the total number of custom objects available for your organization.
Custom setting 2 List

We are familiar with Custom Settings in Salesforce. It is similar to objects which can store records of data. But the major difference is, in Custom Settings the data is saved in Cache and we do not require a SOQL query for fetching the data. Since the data are stored in the cache, it is very fast and efficient. Also, we can set it as public or protected. When we package it for an App, the public type Custom Setting data can be accessed by everyone who has the Profile setting “Customize application” enabled. But if it is protected, then no one will be able to see the Custom Settings. It will be hidden for all the Users. Only the code written in the App can access the data. So this is normally used to store application settings values such as tokens, client IDs, client secrets, etc. We also know that there are two types of Custom Settings.
1)   List
2)   Hierarchy
List Type
List is same as that of a Custom Object which can store data. Normally we can fetch the record from a custom setting using the method ‘getInstance’.
Sample Code for insertion
//Initializing a Custom Setting
App_Settings__c setting = new App_Settings__c();
setting.Name = ‘APP_SETTING’;
setting.access_token__c = ‘sample_token_1234’;
insert setting;
//Get record
App_Settings__c setting = App_Settings__c().getInstance(‘APP_SETTING’);
Here you can see a difference, the record is not fetched based on the Record ID, instead Name field is used. So the Name field is required and should be unique for a List Type Custom Setting.
I think most of us are aware about the list Type and are using it for all types of needs. But there is another type of custom setting called Hierarchy type. Most of us fear to use this Custom Settings. It is not basically because of fear, but because of the lack of knowledge on the usage. So let’s come to the topic.
Hierarchy Type
This is a special type of Custom Setting. There are many advantages of using Hierarchy type Custom Setting. Now consider that you have to incorporate security settings to the users to access the data from a custom setting. What would you do? Anyway, it is difficult to manually provide access level to specific users in List Type. So I’ll explain the advantages of using Hierarchy Type.
One of the main advantages is that we can give hierarchy level access of data to the users. We can give up to three levels which is predefined.
1.    Organization Level       : All users in the Org can access the data.
2.    Profile Level               : All users under the specified Profile can access the data.
3.    User Level          : User specific access of data.
The syntax of using Hierarchy type to get the user instance data in apex is a little bit different from List Type.
Sample Code for insertion
//Initializing a Custom Setting
App_Settings__c setting = new App_Settings__c();
setting.Name = ‘APP_SETTING’;
setting.SetupOwnerId = ‘<User_ID / Profile_ID / Organization_ID>’; // this specifies the access level
setting.access_token__c = ‘sample_token_1234’;
insert setting;
//Get record
App_Settings__c setting = App_Settings__c().getInstance();
As you can see, there is no need of specifying the parameter ‘Name’ in getInstance() method, since it will automatically fetch the corresponding User’s data. If there is no data that corresponds to the user, then it will check whether there is any data assigned to that user’s profile. If there is a data available for that profile, it will be returned; otherwise it will check whether there is any data assigned for the whole organization, if available, then it is returned back or an empty object will be returned. The field ‘SetupOwnerId’ specifies who all can access the data.
The other available methods to manually fetch the data are
getInstance(‘User_ID’) : User Level
getInstance(‘Profile_ID’) : Profile Level
getOrgDefaults() : Organization Level
The next thing is; it can be directly used in Visualforce pages without referencing the apex class.
<apex:outputText value=”{!$Setup.App_Settings__c.Value__c}”/>

And also we can use this directly inside the Custom button JavaScript code
if(‘{!$Setup.App_Settings__c.Value__c }’ == ‘SomeValue’)
{
//Perform action
}
This allows users to access app settings with ease. So to conclude, there are many things which are still unknown to the users. But by exploring them in depth, you can develop almost anything with ease.

And also Check
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_custom_settings.htm

Difference BetweenActionfunction and Remote Action


1. Using action function, you can call only same class function.
2. Remote Action returns the results from the class in Javascript.
3. Action function submit the page, Remote action doesn't


From cloudforce4u.com

Difference between action support and action function

Article 1** Article 2** Article 3** Article 4** Article 5** Article 6** Article 7** Article 8** Article 9  ** Article 10 

Before understanding the difference between Action support and Action Function let us go through what they do and their similarities:

1. Both action support and function can be used to call a controller method using an AJAX request.
   * for example call controller onclick of a inputcheck box
   * or call a controller method onfocus of a input field
Well, they both do the same thing of calling controller method.

Difference between both:


1. Action function can call the controller method from java script.

2. Action support adds AJAX support to another visualforce component and then call the controller method. 
    for example:

    
 <apex:outputpanel id="outptpnl">
             <apex:outputText value="click here"/>
         <apex:actionSupport event="onclick" action="{!controllerMethodName}"  rerender="pgblck" />
     </apex:outputpanel> 
  
Here action support adds AJAX to output panel, so once you click on output panel controller method will be called.
  
3. Action function cannot add AJAX support to another component. But from a particular component which has AJAX support(onclick, onbluretc) action function can be called to call the controller method.
Example:

 <apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/>
 <apex:inputcheckboxonclick="myactionfun" />

In this example onlick of input checkbox "myactionfun" action function is called from where controller method "actionFunMethod" gets called.
Apart from this, the main difference between the "two" action support and action function is that, the action function can also be called from java script.
Example:

<apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/>
 <apex:inputcheckboxonclick="myJavaMethod()" />
<script>
   function myJavaMethod(){
     myactionfun();// this call the action function
  }
  </script>

Here onclick of the inputcheck box java script is called from where the action function gets called and ultimately your controller method.
Lets demo both as a full fledged example:

Click in the Input text to call controller method using action support 
Click the input check box to call Java script, then confirm in java script, upon confirmation controller method is called using action function.

Tex in the lower pageblock gets changed depending on whether the controller method is called by action support or action function. 
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhmoJreA1TmjG5p9NJ4WtrH1fnsubVPwgIfPCyXDbIGzEIuKCeBJ1hKGlI-zQNvWk_YgCvJYQrWloznzQP0gg6idd0UoVl8eYgmjj46IIEu_6AewfjRkSp84k5CXDwD3bl50EjmPmMt1VQ5/s1600/difsupfun.png

Example:

<apex:page controller="ActionSupFunController">
 <apex:form>
  <h1>Demonstration of difference between Action function and Action Support</h1>

  <apex:actionFunction name="myactionfun"  action="{!actionFunMethod}" reRender="outptText"/><br></br><br></br> 
  
  Input Text <apex:inputText>
                <apex:actionSupport action="{!actionSupMethod}" event="onclick" reRender="outptText" />
             </apex:inputText><br></br>
             
Click me to call action function method   <apex:inputcheckboxonclick="myJavaMethod()" /><br></br><br></br>   

    <apex:pageBlock>
        <apex:outputText value="{!Display_This_String}" id="outptText"/>
    </apex:pageBlock>         

  <script>
   function myJavaMethod(){
   varcheckinput = confirm('Are sure you wnat to call action function method?');
   if(checkinput == true) 
      myactionfun();
  }
  </script>
 </apex:form> 
</apex:page>
Class:

Public with sharing class ActionSupFunController {
Public string Display_This_String{get;set;}
    Public ActionSupFunController (){
     Display_This_String = 'value set in constructor';
    }
    
    Public void actionFunMethod(){
      Display_This_String = 'value set in action function method';
    }
    
    Public void actionSupMethod(){
      Display_This_String = 'value set in action Support method';
    }
}

Output:

Demonstration of difference between Action function and Action Support

Input Text 
Click me to call action function method


value set in action function method-----------// it is changed based up on we call  click on the input testbox action support method call click input check box action function call

///////////////////////////////////////////////////////////////////////////////////////////////////////////

Fieldset in salesforce

What is a fieldset?

In this section i will explain about what is a fieldset? How can we create that? and how can we use that in a visualforce page?
Fieldset is a grouping of fields, you can use this fieldset in visualforce page to display that group of fields in that page. If you are using field set in visualforce to display fields, then you can add, remove & reorder fields very easily. No need to do code modifications to the page, Infieldset only you can add, remove & reorder fields. Generally these field sets are useful in managed packages. In mangedpackages , If you used field set in visualforce pages, administrators can easily add, remove and reorder fields in page. As an administrator, you can create or edit field sets and also you can edit installed fieldsets.
How to create a fieldset?
To create a fieldset, go to object, you want create fieldset by clicking on new button. Enter required fields and save. We will get below screen to add fields to field set.
Fieldset In Salesforce
Using fieldsets is very easy & you can drag and drop to arrange fields in fieldsets.
How to use field set in a visualforce page?
Below code is simple visualforce, it explains about how to use fieldset in a visualforce page.
<apex:page id=”pageId” standardcontroller=”Registration__c”>
<apex:form id=”formId”>
<apex:pageblock id=”pb”>
<apex:pageBlockSection>
<apex:repeat value=”
{!$ObjectType.Registration__c.FieldSets.Registration_req_fields}” var=”fs”>
<apex:inputfield value=”{!Registration__c[fs]}”>
</apex:inputfield></apex:repeat>
</apex:pageBlockSection>
<apex:pageBlockButtons>
<apex:commandButton value=”Submit Details” action=”{!Save}”/>
</apex:pageBlockButtons>
</apex:pageblock>
</apex:form>
</apex:page>
The above code displays all fields in the field set. See the below screen to see the output of above code.
Fieldset
No need to change the code to re arrange fields in this page. What ever the order you created/edited in field set, the same order will display on this page.
We can easily make fields required. It is drag drop tool like page layout. To make required, double click on the field and check the required check box.
Important point about field sets:
– In the field set, you can span to fields that reference multiple objects. When you span a field into a field set that references multiple objects, the only field you can span to is the Name object.
– The total number of cross object spans within the In the Field Setcontainer can’t exceed 25.


No comments:

Post a Comment