Thursday, December 6, 2012

Standard pop up box in Salesforce using JavaScript

We can make use of alert() in javascript to display the pop in Visualforce page. But there another pop up box which looks pretty good and it is providing by Salesforce.

Below is the code to create a pop up box in Visualforce :

<apex:page >
<script type="text/javascript">
document.body.style.cursor="auto";
var box=new SimpleDialog("Test", true);
box.setTitle("Test Pop up");
box.createDialog();
    box.setContentInnerHTML("<b>Praveen</b><input type=\"button\" value=\"Ok\"  onclick=\"javascript:box.hide();\"/>");
box.show();
</script>
</apex:page>


Calling Force.com REST API from Javascript in Visualforce


Download the Forcetk.js from here and upload it in Static resources. Your Name > App Setup > Develop > Static Resources

 Include the forcetk.js and jquery.js in the Visualforce page in which you would like to call the REST API.


Here is the example code to display the Accounts list using REST API from java script in Visualforce page.


<apex:page standardController="Account">
<apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"/>
<apex:includeScript value="{!URLFOR($Resource.forcetk)}"/>
<script type="text/javascript">
// Get a reference to jQuery that we can work with
$j = jQuery.noConflict();
// Get an instance of the REST API client and set the session ID
var client = new forcetk.Client();
client.setSessionToken('{!$Api.Session_ID}');
var temp="";
client.query("SELECT Name FROM Account", function(response){
for (var i=0;i<response.records.length;i++)
{
    temp=temp+"<br/>"+response.records[i].Name;
}
$j('#accountname').html(temp);  
});
</script>
<p><u><b>Accounts:</b></u><br/><span id="accountname"></span>.</p>
</apex:page>


However it is good, but still this will increase the API calls.

Click here to see more information about the rest calls.

Tuesday, October 16, 2012

Google Translator in Visualforce






2)      Enter your site URL
3)      Click on Next



4)      Click on “Get Code” button


Copy and Paste the above code in the Visualforce page in which you to put the Google Translate languages drop down list.

Treeview in Visualforce using JQuery


Visualforce page code:

<apex:page controller="treeviewcon" sidebar="false" showHeader="false">
<html>
<head>
    <apex:includeScript value="{!URLFOR($Resource.jqueryminjs)}"  />
    <apex:stylesheet value="{!URLFOR($Resource.jquerycss)}"/>
     <apex:stylesheet value="http://jquery.bassistance.de/treeview/jquery.treeview.css"/>
    <apex:includeScript value="http://jquery.bassistance.de/treeview/lib/jquery.js"/>
    <apex:includeScript value="http://jquery.bassistance.de/treeview/lib/jquery.cookie.js"/>
    <apex:includeScript value="http://jquery.bassistance.de/treeview/jquery.treeview.js"/>
    <apex:includeScript value="http://jquery.bassistance.de/treeview/demo/demo.js"/>
  <style type="text/css">
  #browser {
    font-family: Verdana, helvetica, arial, sans-serif;
    font-size: 120%;
    font-weight:bold;
  }
  </style>
  <script>
  $(document).ready(function(){
    $("#browser").treeview();
  });
  </script>
</head>
<body><br/><br/>
<div style="width:300px;margin-left:50px;">
<apex:pageBlock >
  <ul id="browser" class="filetree">
    <apex:repeat value="{!accnts}" var="acc">
    <li class="closed"><span class="folder">{!acc.name}</span>
        <ul>
            <apex:repeat value="{!acc.contacts}" var="c">
            <li><span class="file"><a href="/{!c.id}" target="_blank">{!c.name}</a></span></li>
            </apex:repeat>
        </ul>
    </li>
    </apex:repeat>
   </ul>
   </apex:pageBlock>
   </div>
</body>
</html>
</apex:page>

Controller:

public with sharing class treeviewcon {
    public List<Account> accnts{get; set;}
    public treeviewcon(){
        accnts = [Select id, name,(Select id, name from Contacts) from account];
    }
}

TreeView : 



Wednesday, October 3, 2012

Triggers and Order of Execution



When you save a record with an insert, update, or upsert statement, Salesforce performs the following events in order.

On the server, Salesforce:

1.       Loads the original record from the database or initializes the record for an upsert statement.
2.       Loads the new record field values from the request and overwrites the old values.
If the request came from a standard UI edit page, Salesforce runs system validation to check the record for:
o    Compliance with layout-specific rules
o    Required values at the layout level and field-definition level
§  Valid field formats
§  Maximum field length
Salesforce doesn't perform system validation in this step when the request comes from other sources, such as an Apex application or a SOAP API call.
3.       Executes all before triggers.
4.       Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any user-defined validation rules. The only system validation that Salesforce doesn't run a second time (when the request comes from a standard UI edit page) is the enforcement of layout-specific rules.
5.       Saves the record to the database, but doesn't commit yet.
6.       Executes all after triggers.
7.       Executes assignment rules.
8.       Executes auto-response rules.
9.       Executes workflow rules.
10.   If there are workflow field updates, updates the record again.
11.   If the record was updated with workflow field updates, fires before and after triggers one more time (and only one more time), in addition to standard validations. Custom validation rules are not run again.
12.   Executes escalation rules.
13.   If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
14.   If the parent record is updated, and a grand-parent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Grand-parent record goes through save procedure.
15.   Executes Criteria Based Sharing evaluation.
16.   Commits all DML operations to the database.
17.   Executes post-commit logic, such as sending email.

Additional Considerations
Please note the following when working with triggers:
·         When Enable Validation and Triggers from Lead Convert is selected, if the lead conversion creates an opportunity and the opportunity has Apex before triggers associated with it, the triggers run immediately after the opportunity is created, before the opportunity contact role is created. For more information, see “Customizing Lead Settings” in the Salesforce online help.
·         If you are using before triggers to set Stage and Forecast Category for an opportunity record, the behavior is as follows:
o    If you set Stage and Forecast Category, the opportunity record contains those exact values.
o    If you set Stage but not Forecast Category, the Forecast Category value on the opportunity record defaults to the one associated with trigger Stage.
o    If you reset Stage to a value specified in an API call or incoming from the user interface, the Forecast Category value should also come from the API call or user interface. If no value for Forecast Category is specified and the incoming Stage is different than the trigger Stage, the Forecast Category defaults to the one associated with trigger Stage. If the trigger Stage and incoming Stage are the same, the Forecast Category is not defaulted.
·         If you are cloning an opportunity with products, the following events occur in order:
o    The parent opportunity is saved according to the list of events shown above.
o    The opportunity products are saved according to the list of events shown above.
If any opportunity products contain unique custom fields, you must null them out before cloning the opportunity.
·         Trigger.old contains a version of the objects before the specific update that fired the trigger. However, there is an exception. When a record is updated and subsequently triggers a workflow rule field update, Trigger.old in the last update trigger won’t contain the version of the object immediately prior to the workflow update, but the object before the initial update was made. For example, suppose an existing record has a number field with an initial value of 1. A user updates this field to 10, and a workflow rule field update fires and increments it to 11. In the update trigger that fires after the workflow field update, the field value of the object obtained from Trigger.old is the original value of 1, rather than 10, as would typically be the case.


Tuesday, August 21, 2012

How to display images on the Page Layout ?


Using formula fields we can do this.

To add a custom formula field:

1)    Navigate to the fields area of the appropriate object
2)    Click New in the Custom Fields & Relationships section of the page.
3)    Select the data type for the formula and click next.
4)    Enter field label.
5)    Choose the Choose output type as TEXT and click Next
6)    Select the IMAGE function from the list of functions to insert an image.
7)    Provide the image URL and alt text for the function.
8)    Click Save.

Example:

IMAGE("/servlet/servlet.ImageServer?id=01530000001Rh9w&oid=00De0000000CpgS&lastMod=1311711723000", "Missed")


Thursday, June 28, 2012

Using Schema.getGlobalDescribe() to get list of all fields in Apex


        For Example, We have one dropdown that had options – Lead, Account, Contact, Opportunities and some custom objects. Upon selection of any of this object, all the respective object’s standard and custom fields should be populated in another dropdown. 
This is how we can do it:
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(‘Account’).getDescribe().fields.getMap();
for(String s : objectFields.keySet())
{
      // process s
}

Sunday, June 3, 2012

Salesforce Security


Security Overview:
          Salesforce is built with security as the foundation for the entire service. This foundation includes both protection for your data and applications, and the ability to implement your own security scheme to reflect the structure and needs of your organization.
          The security features of Salesforce provide both strength and flexibility. However, protecting your data is a joint responsibility between you and salesforce.com. The security features in Salesforce enable you to empower your users to do their jobs efficiently, while also limiting exposure of data to the users that need to act upon it. Implement security controls that you think are appropriate for the sensitivity of your data. Your data is protected from unauthorized access from outside your company, and you should also safeguard it from inappropriate usage by your users.
Security Infrastructure:
          One of the core features of a multi-tenant platform is the use of a single pool of computing resources to service the needs of many different customers. Salesforce protects your organization's data from all other customer organizations by using a unique organization identifier, which is associated with each user's session. Once you log in to your organization, your subsequent requests are associated with your organization, using this identifier.
                    Salesforce utilizes some of the most advanced technology for Internet security available today. When you access the application using a Salesforce-supported browser, Secure Socket Layer (SSL) technology protects your information using both server authentication and data encryption, ensuring that your data is safe, secure, and available only to registered users in your organization.
User security:
          Salesforce provides each user in your organization with a unique username and password that must be entered each time a user logs in. Salesforce issues a session cookie only to record encrypted authentication information for the duration of a specific session. The session cookie does not include either the username or password of the user. Salesforce does not use cookies to store other confidential user and session information, but instead implements more advanced security methods based on dynamic data and encoded session IDs.
About passwords:
There are several settings you can configure to ensure that your user's passwords are strong and secure:
·       Password policies—set various password and login policies, such as specifying    an amount of time before all users' passwords expire, the level of complexity required for passwords, and so on.
·       User password expiration—expire the passwords for all the users in your organization (except for users with “Password Never Expires” permission.)
·       User password resets—reset the password for specified users.
·       Login attempts and lockout periods—if a user is locked out of Salesforce due to too many failed login attempts, you can unlock them.
Password requirements:
       A password cannot contain your User Name and cannot match your first or last name.
For all editions, a new organization has the following default password requirements:
·       A password must contain at least eight characters.
·       A password must contain at least one alphabetic character and one number.
·       The answer to the question posed if you forget your password cannot contain   your password.
·       The last three passwords are remembered and cannot be reused when you are changing your password.

User authentication:
          Salesforce has its own system of user authentication, but some companies prefer to use an existing single sign-on capability to simplify and standardize their user authentication. You have two options to implement single sign-on—federated authentication using Security Assertion Markup Language (SAML) or delegated authentication.


§  Federated authentication using Security Assertion Markup Language (SAML) allows you to send authentication and authorization data between affiliated but unrelated Web services. This enables you to sign-on to Salesforce from a client application. Federated authentication using SAML is enabled by default for your organization.
§  Delegated authentication single sign-on enables you to integrate Salesforce with an authentication method that you choose. This enables you to integrate authentication with your LDAP (Lightweight Directory Access Protocol) server, or perform single sign-on by authenticating using a token instead of a password. You manage delegated authentication at the profile level, allowing some users to use delegated authentication, while other users continue to use their Salesforce-managed password. Delegated authentication is set by profile, not organization wide. You must request that this feature be enabled by salesforce.com. Contact salesforce.com to enable delegated authentication single sign-on for your organization.
The primary reasons for using delegated authentication include:
·       Using a stronger type of user authentication, such as integration with a secure identity provider
·       Making your login page private and not part of the general Internet, but rather, part of your corporate network, behind your corporate firewall
·       Differentiating your organization from all other organizations that use Salesforce in order to reduce phishing attacks.

Network-based Security:
          User authentication determines who can log in, while network-based security limits where they can log in from and when. Use network-based security to limit the window of opportunity for an attacker by restricting the origin of user logins. Network-based security can also make it more difficult for an attacker to use stolen credentials.
          To enhance network-based security, Salesforce includes the ability to restrict the hours during which users can log in and the range of IP addresses from which they can log in. If IP address restrictions are defined for a user's profile and a login originates from an unknown IP address, Salesforce does not allow the login. This helps to protect your data from unauthorized access and “phishing” attacks.
          To set the organization-wide list of trusted IP addresses from which users can always log in without a login challenge. To restrict login hours by profile, or to restrict logins by IP addresses for specific profiles.
Session Security:
          After logging in, a user establishes a session with the platform. Use session security to limit exposure to your network when a user leaves their computer unattended while still logged on. It also limits the risk of internal attacks, such as when one employee tries to use another employee's session.
          You can control the session expiration time window for user logins. Session expiration allows you to select a timeout for user sessions. The default session timeout is two hours of inactivity. When the session timeout is reached, users are prompted with a dialog that allows them to log out or continue working. If they do not respond to this prompt, they are automatically logged out.
Securing Data Access:
Choosing the data set that each user or group of users can see is one of the key decisions that affects data security. You need to find a balance between limiting access to data, thereby limiting risk of stolen or misused data, versus the convenience of data access for your users.
To enable users to do their job without exposing data that they do not need to see, Salesforce provides a flexible, layered sharing design that allows you to expose different data sets to different sets of users.
§  To specify the objects that users can access, you can assign profiles.
§  To specify the fields that users can access, you can use field-level security.
§  To specify the individual records that users can view and edit, you can set your organization-wide sharing settings, define a role hierarchy, and create sharing rules.
The following describes these security and sharing settings:
Object-level security provides the bluntest way to control data. Using object-level security you can prevent a user from seeing, creating, editing, or deleting any instance of a particular type of object, such as a lead or opportunity. Object-level security lets you hide whole tabs and objects from particular users, so that they don't even know that type of data exists.
          You specify object-level security settings in profiles. A profile is a collection of settings and permissions that determine what a user can do in the application, similar to a group in a Windows network, where all of the members of the group have the same folder permissions and access to the same software.
          Profiles are typically defined by a user's job function (for example, system administrator or sales representative), but you can have profiles for anything that makes sense for your organization. A profile can be assigned to many users, but a user can be assigned to only one profile at a time. It's worth taking time up-front to align your various user sets with profiles, depending on what they need to see and do in the application.
In some cases, you may want users to have access to an object, but limit their access to individual fields in that object. Field-level security controls whether a user can see, edit, and delete the value for a particular field on an object. It lets you protect sensitive fields without having to hide the whole object from users. Field-level security is also controlled in profiles.
Unlike page layouts, which only control the visibility of fields on detail and edit pages, field-level security controls the visibility of fields in any part of the app, including related lists, list views, reports, and search results. To ensure that a user can't access a particular field, use field-level security settings. No other settings provide the same level of protection for a field. Important
Field-level security doesn't prevent searching on the values in a field. To set up your organization to prevent users from searching and retrieving records that match a value in a field hidden by field-level security, contact salesforce.com Customer Support.
Record-Level Security (Sharing)
After setting object- and field-level access permissions, you may want to configure access settings for the actual records themselves. Record-level security lets you give users access to some object records, but not others. Every record is owned by a user or a queue. The owner has full access to the record. In a hierarchy, users higher in the hierarchy (such as managers in a role hierarchy) always have access to the data visible to users below them in the hierarchy. This access applies to records owned by users, as well as records shared with them.
          To specify record-level security, set your organization-wide sharing settings, define a hierarchy, and create sharing rules.
§  Organization-wide sharing settings—The first step in record-level security is to determine the organization-wide sharing settings for each object. Organization-wide sharing settings specify the default level of access users have to each others' records.
You use organization-wide sharing settings to lock down your data to the most restrictive level, and then use the other record-level security and sharing tools to selectively give access to other users. For example, let's say users have object-level permissions to read and edit opportunities, and the organization-wide sharing setting is Read-Only. By default, those users can read all opportunity records, but can't edit any unless they own the record or are granted additional permissions.
§  Role hierarchy—Once you've specified organization-wide sharing settings, the first way you can give wider access to records is with a role hierarchy. Similar to an organization chart, a role hierarchy represents a level of data access that a user or group of users needs. The role hierarchy ensures that managers always have access to the same data as their employees, regardless of the organization-wide default settings. Role hierarchies don't have to match your organization chart exactly. Instead, each role in the hierarchy should represent a level of data access that a user or group of users needs.
You can also use a territory hierarchy to share access to records. A territory hierarchy grants users access to records based on criteria such as zip code, industry, revenue, or a custom field that is relevant to your business. For example, you could create a territory hierarchy in which a user with the “North America” role has access to different data than users with the “Canada” and “United States” roles.
Note:
     Although it's easy to confuse profiles with roles, they control two very different things. Profiles control a user's object- and field-level access permissions. Roles primarily control a user's record-level access through role hierarchy and sharing rules.
§  Sharing rules—Sharing rules let you make automatic exceptions to organization-wide sharing settings for particular sets of users, to give them access to records they don't own or can't normally see. Sharing rules, like role hierarchies, are only used to give additional users access to records—they can't be stricter than your organization-wide default settings.
§  Manual sharingSometimes it's impossible to define a consistent group of users who need access to a particular set of records. In those situations, record owners can use manual sharing to give read and edit permissions to users who would not have access to the record any other way. Although manual sharing isn't automated like organization-wide sharing settings, role hierarchies, or sharing rules, it gives record owners the flexibility to share particular records with users that need to see them.
§  Apex managed sharing—If sharing rules and manual sharing don't give you the control you need, you can use Apex managed sharing. Apex managed sharing allows developers to programmatically share custom objects. When you use Apex managed sharing to share a custom object, only users with the “Modify All Data” permission can add or change the sharing on the custom object's record, and the sharing access is maintained across record owner changes.
Creating Predefined Case Teams and Assigning Case Teams to Cases using APEX


Trigger to Create Case Team Member Role:

Trigger CreateMemberRole on user (before insert,before update)
{
caseteamrole cr=new caseteamrole();
cr.accesslevel='edit';
cr.name='test';
cr. PreferencesVisibleInCSP=true;
insert(cr);
}

Trigger to Create Predefined Case Team:

trigger CreateCaseTeam on User (before insert,before update) 
{
caseteamtemplate ct;
caseteamrole cr;
caseteamtemplate c;
try{
cr=[select id from caseteamrole where name=:'test'];
ct=[select id,name from caseteamtemplate where name=:'test'];
c=ct;
}
catch(Exception e)
{
if(ct==null)
{
//create case team template
c=new caseteamtemplate(); 
c.Description='test';
c.Name='test';
insert(c);
}
}
//add case team member to pre defined case team
caseteamtemplatemember cm=new caseteamtemplatemember();
cm.memberid=trigger.new[0].id;
cm.teamroleid=cr.id;
cm.teamtemplateid=c.id;
insert(cm);
}

caseteamtemplaterecord cttr=new caseteamtemplaterecord();
cttr.parentid=trigger.new[0].id;
caseteamtemplate ct=[select id from caseteamtemplate where name=:'test'];
cttr.teamtemplateid=ct.id;
}


Assigning Case Team to a Case:

Trigger AssignToCase on user (before insert,before update)
{
caseteamrole cr=new caseteamrole();
cr.accesslevel='edit';
cr.name='test';
cr. PreferencesVisibleInCSP=true;
insert(cr);
}




Monday, March 12, 2012

Pop up box in Visuaforce

Displaying popup box in Visualforce:

VF Code:

<apex:page controller="tstpopup">
    <apex:form >
        <apex:pageBlock >
        <apex:pageBlockSection >
        <apex:pageBlockSectionItem >
        <apex:commandButton value="Show" action="{!showPopup}" rerender="tstpopup"/>
        </apex:pageBlockSectionItem>
        <apex:pageBlockSectionItem >
        <apex:outputtext value="{!distext}" />
        </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:outputPanel id="tstpopup">
        <apex:outputPanel styleClass="popupBackground" layout="block" rendered="{!displayPopUp}"/>
        <apex:outputPanel styleClass="custPopup" layout="block" rendered="{!displayPopUp}">
        <apex:pageBlock >
        <apex:pageblockSection columns="1">
        <apex:pageblockSectionItem >
        <apex:outputLabel value="Subject" id="sub"/>
        <apex:inputText value="{!textarea1}"/>
        </apex:pageblockSectionItem>
        <apex:pageBlockSectionItem >
        <apex:outputLabel value="Description"/>
        <apex:inputTextarea value="{!descr}"/>
        </apex:pageBlockSectionItem>
        </apex:pageblockSection>
        </apex:pageBlock>
        <apex:commandButton value="Hide" action="{!closePopup}" rerender="tstpopup"/>
        </apex:outputPanel>
        </apex:outputPanel>
     </apex:form>
    <style type="text/css">
        .custPopup{
            background-color: white;
            border-width: 2px;
            border-style: solid;
            z-index: 9999;
            left: 50%;
            padding:10px;
            position: absolute;
            /* These are the 3 css properties you will need to change so the popup
            displays in the center of the screen. First set the width. Then set
            margin-left to negative half of what the width is. You can add
            the height property for a fixed size pop up if you want.*/
            width: 500px;
            margin-left: -250px;
            top:100px;
        }
        .popupBackground{
            background-color:black;
            opacity: 0.20;
            filter: alpha(opacity = 20);
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: 9998;
        }
    </style>
</apex:page>

Controller Code:


public class tstpopup
{
    public String distext { get; set; }
    public String descr { get; set; }
    public String textarea1 { get; set; }
    public boolean displayPopup {get; set;}      
    public void closePopup()
    {      
        displayPopup = false;
    }  
    public void showPopup()
    {      
        displayPopup = true;  
    }
    public void getdistext()
    {
        distext='praveen';//textarea1+'\n'+descr;
    }
}