Browse Author: ankit.shah

How to use Visualforce IDs in jQuery

Prerequisites:

You will need to download the jQuery and jQuery UI libraries. jQuery is the core library which offers DOM manipulation methods and jQuery UI is a higher level library which constructs widgets for use on your page. From the jQuery UI site, you can download a zip tailored to the portions of the libraries you need.Once you have the ZIP in hand, you’ll need to upload it as a static resource.

About Using jQuery:

To access jQuery in your Visualforce pages, you then need to include the libraries with something like this:
<apex:includeScript value=”{!URLFOR($Resource.jQuery, ‘/js/jquery-1.4.2.min.js’)}”/>
<apex:includeScript value={!URLFOR($Resource.jQuery, ‘/js/jquery-ui-1.8.6.custom.min.js’)}”/>
<apex:stylesheet value=”{!URLFOR($Resource.jQuery, ‘/css/ui-lightness/jquery-ui-1.8.6.custom.css’)}”/>

else you can directly use  the Google AJAX Libraries content delivery network to serve jQuery to your users directly from Google’s network of datacenters.

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”></script>
<script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js”></script>

To use jQuery within Force.com, you’ll need to make use of the jQuery.noConflict() function to reassign jQuery’s global variable to something which won’t conflict with any other libraries which may already be in use (including standard, native libraries used within Visualforce). You’ll see an example of this in the code below.

var j$ = jQuery.noConflict();

j$(document).ready(function()      {     //your actions  };

To use Visualforce Id’s with jquery there is somewhat different approach as compared to simple HTML element Id’s. You have to use selector as follows:

var compid = j$(“[id $=’skillpanel2′]”);
Now you can use this variable to perform actions on the elements.
like,

compid.hide(); // will hide the element.

Example:

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js”></script>

<script src=”https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js”></script>

<script>
var j$ = jQuery.noConflict();
j$(document).ready(function(){var compid = j$(“[id $=’skillpanel2′]”);
compid.hide();
});
</script>

Relationship in Salesforce

When two objects are related in the database, they are linked together by a relationship field. This allows you to associate related information easily between objects. All relationships maintain some form of a parent-child relationship. This can be thought of as a hierarchical structure where one object looks up to the other, and as such, you only need to create one relationship field. You create a relationship field in the child object. In order to determine the parent, you need to consider which object is dependant on the other and how many records of both objects could possibly be related to each other in your data model.

There are two main buckets for categorizing potential relationships: either a one-to-many or many-to-many relationship. Both of these describe how many children can be associated to their related parent. The two fields available for creating these kinds of relationships in the database, lookup and master-detail, have unique characteristics regarding how they handle data deletion, record ownership, security, and required fields. When deciding between these two types of relationships, you need to think about which type of field will hold the kind of functionality you are looking for.

One-to-Many

One-to-many means there is one parent record with the potential to be related to many child records. The first way to accomplish this would be to create a lookup field. A lookup field links two objects together, but has no effect on deletion or security. This means when you define a lookup relationship, data from the child object can appear as a custom related list on page layouts for the parent object; however, you are not required to populate the lookup field on creation of a child record. Conversely, if you delete the parent record, the child record will still exist, but the field referencing the deleted record by default will be cleared. As of Summer ’12, a few lookup field enhancements have been added to allow for more granular control on response actions when handling deletions.

In the example below, we can see projects and team members. Team members can be a part of a project, but are not required to be a part of one. A project can have many team members, but a team member can only be a part of one project. Therefore, this type of relationship would be a lookup relationship.

The second way to create a one-to-many relationship is with a master-detail relationship field. This is when the master (parent) object controls certain behaviors of the detail (child) object. First, when a record of the master object is deleted, its related detail records are also deleted. Secondly, the Owner field on the detail object is not available and is automatically set to the owner of its associated master record. Third, the detail record inherits the sharing and security settings of its master record. The master-detail relationship field is required on creation of all child records.

In the picture below you can see to do items are linked to team members. To do items must always be related to a team member, and if the team member were deleted, their to do items would become irrelevant. Therefore, this relationship would be a master-detail relationship.

 

Many-to-Many

The many-to-many relationship is a bit more complicated. A many-to-many relationship allows each record of one object to be linked to multiple records from another object and vice versa. In this case, you need to create a junction object, which will create a unique link for every instance that you relate a parent object to a child. To build out a many-to-many relationship, create a custom junction object with two master-detail relationship fields linking to the objects you want to relate.

In the example below, we still have projects and team members with related to do items, but in this case team members can be a part of multiple projects. Projects can have several team members, and team members can be a part of several projects. Conversely, both objects are not required to be related. A team member can be a lone wolf and not participate in any projects, and a project does not need to have team members. Therefore, instead of having a lookup field linking projects and team members like the one-to-many case, we must build a junction object that will create a unique record for every instance where a team member joins a project. This junction, called project team member, is illustrated in the diagram below.

 

Using URLFOR function in Apex Salesforce

While developing your Visualforce pages you may need to be able to obtain the URL of certain actions or your static resources.

I found it personally a challenge since the documentation for “URLFOR” function is not included in “Visualforce Developer Guide” itself and instead included in the general help area of Salesforce.

Generally you can use the “URLFOR” function for two purposes:

  1. Obtain URL of a static resource
  2. Obtain URL of an object’s action

In this article I will demonstrate usages of the two above.

Generally, URLFOR function returns a relative URL for an action, s-control, or a file in a static resource archive in a Visualforce page. Following the syntax of the function:

{!URLFOR(targetid, [inputs], [no override])}

Parameters shown in brackets ([]) are optional.

  • target: You can replace target with a URL or action, s-control or static resource.
  • id: This is id of the object or resource name (string type) in support of the provided target.
  • inputs: Any additional URL parameters you need to pass you can use this parameter.
    you will to put the URL parameters in brackets and separate them with commas
    ex: [param1=”value1″, param2=”value2″]
  • no override: A Boolean value which defaults to false, it applies to targets for standard Salesforce pages. Replace “no override” with “true” when you want to display a standard Salesforce page regardless of whether you have defined an override for it elsewhere.

Obtaining URL of a Static Resource

<!– Use $Resource global veriable to reference your resource file –>
<apex:image url=”{!URLFOR($Resource.LogoImg)}” width=”50″ height=”50″ />

<!– If your file is in another ZIP file, then pass the path of the file as id to URLFOR –>
<apex:image url=”{!URLFOR($Resource.CorpZip, ‘images/logo.gif’)}” width=”50″ height=”50″ />

Obtaining URLs of an Object’s Actions:
In order to get URL of the an object’s actions you need to know what actions that object supports. Below are some of the common actions most Objects support:

  • View: Shows the detail page of an object
  • Edit: Shows the object in Edit mode
  • Delete: URL for deleting an object
  • New: URL to create a new record of an object
  • Tab: URL to the home page of an object

However, each object may support additional actions for example Contact also supports “Clone” action and Case supports “CloseCase” action.
<!– Use $Action global varialble to access the New action reference –>
<apex:outputLink value=”{!URLFOR($Action.Account.New)}”>New</apex:outputLink>
<br/>
<!– View action requires the id parameter, a standard controller can be used to obtain the id –>
<apex:outputLink value=”{!URLFOR($Action.Account.view, account.id)}”>View</apex:outputLink>
<br/>
<!– Edit action requires the id parameter, id is taken from standard controller in this example –>
<apex:outputLink value=”{!URLFOR($Action.Account.Edit,account.id)}”>Edit</apex:outputLink>
<br/>
<!– Delete action requires the id parameter, also a confirm message is added to prevent deleting the record when clicked by mistake –>
<apex:outputLink value=”{!URLFOR($Action.Account.delete, account.id)}” onclick=”return window.confirm(‘Are you sure?’);”>Delete</apex:outputLink>
<br/>
<!– From all custom buttons, links, s-controls and visualforce pages you can use the following to get the link of the object’s homepage –>
<apex:outputLink value= “!URLFOR($Action.Account.Tab,$ObjectType.Account)}”>Home</apex:outputLink>

 

 

Using component in Visualforce

Some Visualforce components, such as <apex:pageBlockTable> or <apex:dataTable>, allow you to display information from multiple records at a time by iterating over a collection of records. To illustrate this concept, the following page uses the <apex:pageBlockTable> component to list the available job positions:

Visual Force Code:
<apex:pageblocktable value=”{!lstObjects}” var=”posts”>
<apex:column headerValue=”Name”> <apex:outputLink value=” !URLFOR($Action.positions__c.View,posts.id)}” target=”_blank”>{!posts.position_title}</apex:outputLink>
</apex:column>
<apex:column value=”{!posts.status}” headerValue=”Status”/>
<apex:column value=”{!posts.state}” headerValue=”State”/>
<apex:column value=”{!posts.city}” headerValue=”City”/>
<apex:column value=”{!posts.min_exp}yrs ” headerValue=”Experience Required”/>
<apex:column value=”{!posts.industry}” headerValue=”Industry”/>
<apex:column headerValue=”View Candidates”>
<apex:outputLink value=”/apex/Position_View”>View
<apex:param name=”position” value=”{!posts.position_title}”/>
</apex:outputLink>
</apex:column>
</apex:pageblocktable>

APEX code:
public class PositionSearch
{
List<positions__c> retresults = new List<positions__c>();
public List<PositionSearch> lstObjects {get; set;}
public PageReference defaultPositions()
{
lstObjects = new List<PositionSearch>();
retResults = [Select id, name,status__c,state__c, city__c,experience__c,industry__c from positions__c];        for(positions__c pos: retResults)
{
PositionSearch tmp = new PositionSearch();
tmp.position_title = pos.name;
tmp.state = pos.state__c;
tmp.city = pos.city__c;
tmp.industry = pos.industry__c;
tmp.status = pos.status__c;
tmp.min_exp = pos.experience__c;
tmp.id = pos.id;
lstObjects.Add(tmp);
}
return null;
}
}

The <apex:pageBlockTable> Component

Like other iteration components, <apex:pageBlockTable> includes two required attributes, value and var:

  • value takes a list of sObject records or values of any other Apex type. In the example above, {!lstObjects} is the list of queried data.
  • var specifies the name of the iteration variable. This variable is used within the body of the <apex:pageBlockTable> tag to access the fields on each contact. In this example, value=”{!posts}” is used on the <apex:column> tag to iterate through the returned list.

Note:
The <apex:pageBlockTable> component automatically takes on the styling of a standard Salesforce list. To display a list with your own styling, use <apex:dataTable> instead.

 

 

 


Creating Dependent SelectLists in VisualForce

We can create the SelectLists in VisualForce whose values will depend on the value selected in another selectlist.The method i have used here is using the Lists collection by programatically filling the values of the dependant selectlist based on the selected value.

VisualForce code:
<apex:outputLabel value=”Select State”‘>
<apex:selectList value=”{!selectedLevel1}” id=”cbxlevel1″ size=”1″ required=”true”>
<apex:selectOptions value=”{!level1items}”/>
<apex:actionSupport event=”onchange” rerender=”cbxlevel2″/>
</apex:selectList>

<apex:outputLabel value=”Select City”‘>
<apex:selectList value=”{!selectedLevel2}” id=”cbxlevel2″ size=”1″>
<apex:selectOptions value=”{!level2items}”/>
</apex:selectList>

Here in the code above, when the value of ‘State’ is selected it will populate the values in City SelectList.

APEX code:
public string selectedLevel1 {get; set;}
public string selectedLevel2 {get; set;}

public List<selectOption> level1Items {
get {
List<selectOption> options = new List<selectOption>();
options.add(new SelectOption(‘Select’,’Select’));
for(resumes__c res : [select state__c from resumes__c])
options.add(new SelectOption(res.state__c,res.state__c));
return options;
}
set;
}

Above is the code that returns the List of values to be populated in the SelectLists.

Uploading a document in apex salesforce using custom controller

sometimes you may want to create a process where uploading a document is mandatory. You can create a single Visualforce page with all of the fields for the record plus the field required to upload a document. code  below is an example

//VISUALFORCE PAGE
<apex:page controller=”docex”>
<apex:outputLabel value=”Document Name”/>
<apex:inputText id=”name” value=”{!d.name}”/>

<apex:outputLabel value=”Upload Document”/>
<apex:inputFile value=”{!file}” />
<apex:commandButton value=”Save” action=”{!insert}” id=”save”/>
</apex:page>

//APEX CLASS
public class docex
{
Document d{get;set;}
public ID folderid{get;set;}

public docex
{
d= new Document();
}
public void insert()
{
//document
folderid=UserInfo.getUserId();    //uses the current user id as folder id
d.body=file;            // body field in document object which holds the file.
d.folderid=folderid;        //folderid where the document will be stored
insert d;
}

}

for further reference you can store the id of an document along with other fields in your custom object . and retrieve the contents of the document object by using soql query:

document d=[select body, id , name from document where id=”<stored 18 character id>”]


Need more help?

Hi there, was your problem or query resolved? If not & need more assistance, please do reach out to us at info@nanostuffs.com, we'll be more than delighted to help. Nanostuffs has 7+ years of extensive Salesforce & iOS/Android experience.
Holler Box