A few weeks back i was looking around the appexchange to find some cool chatter apps, and i found these two which were awesome.
ChatterBot Auto response:
Install:
This app acts as a bot and responds to chatter posts based upon keyword match. It also has other cool features like automatic case creation from a chatter post. Moreover, the code is written generically. So, it's pretty easy to extend and adapt to specific needs.
Auto Response:
I just set up an auto response rule to point users to a help document link when their chatter post contains "chatter email settings". Here is a snapshot of the rule
And here is a screencap after the BOT in work.
Automatic Case Creation from chatter posts:
If your chatter posts contains the keyword {!case}, the BOT creates a case and gives the case number as a comment to your post. Here's one in action.
Note: I created a user called ChatterBot, and started the Bot jobs as this user. Also, the BOT's work on scheduled intervals (every 1 hour i guess), you can also run it manually on the click of a button.
Chatter Swarm 3:
Install
This app allows setting up rules for automatically following Accounts, Cases Opportunities etc and custom objects too.
Here's a new swarm rule which says that when a Lead is updated or created with a status of "Working - Contacted", then the Lead needs to be automatically followed by two users.
The Swarm in action.
Note that you could set up rules for Lead, Opportunity, Cases and chatter posts.
ChatterBot Auto response:
Install:
This app acts as a bot and responds to chatter posts based upon keyword match. It also has other cool features like automatic case creation from a chatter post. Moreover, the code is written generically. So, it's pretty easy to extend and adapt to specific needs.
Auto Response:
I just set up an auto response rule to point users to a help document link when their chatter post contains "chatter email settings". Here is a snapshot of the rule
And here is a screencap after the BOT in work.
Automatic Case Creation from chatter posts:
If your chatter posts contains the keyword {!case}, the BOT creates a case and gives the case number as a comment to your post. Here's one in action.
Note: I created a user called ChatterBot, and started the Bot jobs as this user. Also, the BOT's work on scheduled intervals (every 1 hour i guess), you can also run it manually on the click of a button.
Chatter Swarm 3:
Install
This app allows setting up rules for automatically following Accounts, Cases Opportunities etc and custom objects too.
Here's a new swarm rule which says that when a Lead is updated or created with a status of "Working - Contacted", then the Lead needs to be automatically followed by two users.
The Swarm in action.
Note that you could set up rules for Lead, Opportunity, Cases and chatter posts.
Whenever a user creates a new Account, Contact, Opportunity or any custom object record it is sometimes required to automatically populate certain fields with values.
You could do this by setting the "default" value on a text field. However, there are number of restrictions. One workaround would be to use Workflow rules for field updates, but remember workflow rules are fired only after you hit the "Save" button
Let's say that you would want the default value of the "Billing Country" field on Account to be set to "India". The video below shows how to do this by passing values through the URL.
P.S: This is not a best practice, but just in case it might help in some situations. You could override the "New" button and pass parameters through the URL.
You could do this by setting the "default" value on a text field. However, there are number of restrictions. One workaround would be to use Workflow rules for field updates, but remember workflow rules are fired only after you hit the "Save" button
Let's say that you would want the default value of the "Billing Country" field on Account to be set to "India". The video below shows how to do this by passing values through the URL.
P.S: This is not a best practice, but just in case it might help in some situations. You could override the "New" button and pass parameters through the URL.
UPDATE: With the Spring 2013 release, the steps described below have become bit more complicated.
The Show/Hide Chatter toggle sometimes might make the page look too long. When you have a lot of chatter going on, the page becomes really big and your detail page or the home page goes way down under.
Even when you can't control the size of your chatter frame, hiding it by default would be ideal i think. And so, this bit of code. Add this code to a home page component, to a visualforce page, or add it to a visualforce page and embed it within standard page layouts.
Use this, when you have chatter inside a visualforce page. Make sure that this code gets called after the entire page has loaded. Pasting this code towards the end of the visualforce page should be fine. In case it doesn't work, put the code inside a function and call the function after page load using "window.onload = functionname();"
var e = document.getElementById("showFeedLink");
if(e.style.display == "none")
chatter.getFeed().toggle('{"subjectId":"a4MV00000032ixk","feedType":"ENTITY"}', false);
The portion marked in RED denotes the record ID.Use this, when you want to hide chatter in the home page. Create a new Home Page Component and select "HTML Area" and then check the "Show HTML" checkbox and paste this code.
function hidechatter()
{
var e = document.getElementById("showFeedLink");
if(e.style.display == "none")
chatter.getFeed().toggle('{"subjectId":"a4MV00000032ixk","feedType":"NEWS"}', false);
}
window.setTimeout("hidechatter()", 2000);
}
The portion marked in RED denotes the USER ID.
The below diagram is what we are going to build. This hierarchy is based upon the manager field in the user object. The below example is NOT based upon the role hierarchy. Anyhow, you can modify the code below to fit the role hierarchy.
Visualforce Page:
Visualforce Page:
<apex:page controller="orgchart" showHeader="false">
<html>
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {packages:['orgchart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
data.addRows([
{!userdata}
]);
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, {allowHtml:true});
}
</script>
</head>
<body>
<div id='chart_div' style="font-size:18px;"></div>
</body>
</html></apex:page>
Apex Class
public class orgchart {
Public String getuserdata()
{
List<User> allusers = [Select Name,Manager.Name from User where IsActive = TRUE and ManagerId != NULL];
String datastr = '';
for (integer i=0;i<allusers.size();i++)
{
datastr = datastr + '[\'';
datastr += allusers[i].Name;
datastr+= '\',\'';
datastr+= allusers[i].Manager.Name;
datastr+='\',\'\'],';
}
datastr = datastr + '';
return datastr;
}
}
I wanted to run a report to fetch all users in our salesforce org and then group them by their License type.
Problem with Standard Report: You can use the Standard report on the User object and use the "UserType" field. But the problem is that this field is not very specific. For instance, this field has a type name "Salesforce" for both the "Salesforce" license type and the "Salesforce Platform" license type.
To get a more in-depth report, i used the Apex Data Loader and exported data from a few objects to arrive at the final report.
Objects to consider:
Profile:
API doc http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_profile.htm
Field: UserLicenseId
User:
API doc:http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_user.htm
Field: ProfileId
UserLicense:
API doc: http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_userlicense.htm
Field: LicenseDefinitionKey
Open Apex Data Loader. Select "Export" and select the object "User" and paste the following query.
Problem with Standard Report: You can use the Standard report on the User object and use the "UserType" field. But the problem is that this field is not very specific. For instance, this field has a type name "Salesforce" for both the "Salesforce" license type and the "Salesforce Platform" license type.
To get a more in-depth report, i used the Apex Data Loader and exported data from a few objects to arrive at the final report.
Objects to consider:
Profile:
API doc http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_profile.htm
Field: UserLicenseId
User:
API doc:http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_user.htm
Field: ProfileId
UserLicense:
API doc: http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_userlicense.htm
Field: LicenseDefinitionKey
Open Apex Data Loader. Select "Export" and select the object "User" and paste the following query.
Select Id,Name,Profile.Name,Role.Name,Profile.UserLicenseId from User
Open Apex Data Loader. Select "Export" and select the checkbox "Show all Salesforce objects". Now, select the object "UserLicense" and paste the following query.
Select LicenseDefinitionKey,Name from UserLicense
Now, do a "Excel Vlookup" between the Profile.UserLiceseId column in the first csv file and the "LicenseDefinitionKey" in the second csv file. The Name column in the second csv file denotes the actual salesforce license Name.
If you are not familiar with Vlookup, then watch this video
Note:I tried this only with the LEN function and i hope it works with other formula functions as well.
My requirement:
I wanted to calculate the length of a couple of fields of data type Text Area, and put the number into a new field.
As usual, i created a formula field and used the LEN function. When i tried to INSERT my Long Text Area fields, they were not available for selection. I later found out that you cannot use Long Text Area fields in formulas as of now. Hope that it becomes available soon, until then here is a workaround.
Let's say that i have an object named "MyCustomObject__c". I want to calculate the sum of the length of the Long Text Area fields Field1__c, Field2__c, Field3__c and put the value into SumofLenght__c
STEP 1: Create a new field on the object MyCustomObject__c named "SumofLength__c" of datatype "Number".
STEP 2: Create a new Workflow rule on the object "MyCustomObject__c"
Evaluation Criteria: Every time a record is created or edited
Rule Criteria: MyCustomOject Name: NOT equal to NULL
STEP 3:
Create a Workflow Field Update as below
My requirement:
I wanted to calculate the length of a couple of fields of data type Text Area, and put the number into a new field.
As usual, i created a formula field and used the LEN function. When i tried to INSERT my Long Text Area fields, they were not available for selection. I later found out that you cannot use Long Text Area fields in formulas as of now. Hope that it becomes available soon, until then here is a workaround.
Let's say that i have an object named "MyCustomObject__c". I want to calculate the sum of the length of the Long Text Area fields Field1__c, Field2__c, Field3__c and put the value into SumofLenght__c
STEP 1: Create a new field on the object MyCustomObject__c named "SumofLength__c" of datatype "Number".
STEP 2: Create a new Workflow rule on the object "MyCustomObject__c"
Evaluation Criteria: Every time a record is created or edited
Rule Criteria: MyCustomOject Name: NOT equal to NULL
STEP 3:
Create a Workflow Field Update as below
So, i did a data export from salesforce.com and wanted to get the month from a date time field...
The general format of DateTime fields is like this 2012-01-15T18:34:00.000Z
If suppose you have this in column D in excel, just type in the following formula in an adjacent column
Say you do it in E1
=SUBSTITUTE(SUBSTITUTE(D1,”T”,” “),”.000Z”,”")
This eliminates the time part and you just get the date value....
Now, simply double-click on the bottom edge of E1 and the formula would be applied to the entire column E.
Now, E might still represent some number... Select the entire E column, right click and select "Format Cells" and select the category as "Date"...
To fetch the Day, Month and Year from column E, use the formulas = DAY(E1), =MONTH(E1), =YEAR(E1) ...
The general format of DateTime fields is like this 2012-01-15T18:34:00.000Z
If suppose you have this in column D in excel, just type in the following formula in an adjacent column
Say you do it in E1
=SUBSTITUTE(SUBSTITUTE(D1,”T”,” “),”.000Z”,”")
This eliminates the time part and you just get the date value....
Now, simply double-click on the bottom edge of E1 and the formula would be applied to the entire column E.
Now, E might still represent some number... Select the entire E column, right click and select "Format Cells" and select the category as "Date"...
To fetch the Day, Month and Year from column E, use the formulas = DAY(E1), =MONTH(E1), =YEAR(E1) ...
VF dashboards
Advanced reporting and Dashboards in Salesforce: Google Visualization with Visualforce
3:35 PMIf you haven't yet tried your hand with Google Visualization API's this is the best time to start...
Here is the link to the documentation to get started .. http://code.google.com/apis/chart/interactive/docs/reference.html
A very cool feature of this is you could generate charts just by passing parameters in the URL.
It's as simple as this, click the link https://chart.googleapis.com/chart?cht=p3&chs=450x100&chd=t:30,20,20,15,15&chl=Open|In Progress|On Hold|Pending Confirmation|Closed
As you can see, the values in PINK color are the actual segments of the chart. You may split the entire 100% as per your req, and the text in GREEN is the value for each of the segments.
How can i use this?
Well, you could just embed this into a Standard Page Layout using just a formula field. So, you get a real time snapshot right inside your detail page.
Also, you could do some complex calculations in your apex class and pass the results of the calculation to the URL as parameters and you have a nice little graph.
Refer to the documentation for more samples and chart types. http://code.google.com/apis/chart/interactive/docs/reference.html
Here is the link to the documentation to get started .. http://code.google.com/apis/chart/interactive/docs/reference.html
A very cool feature of this is you could generate charts just by passing parameters in the URL.
It's as simple as this, click the link https://chart.googleapis.com/chart?cht=p3&chs=450x100&chd=t:30,20,20,15,15&chl=Open|In Progress|On Hold|Pending Confirmation|Closed
As you can see, the values in PINK color are the actual segments of the chart. You may split the entire 100% as per your req, and the text in GREEN is the value for each of the segments.
How can i use this?
Well, you could just embed this into a Standard Page Layout using just a formula field. So, you get a real time snapshot right inside your detail page.
Also, you could do some complex calculations in your apex class and pass the results of the calculation to the URL as parameters and you have a nice little graph.
Refer to the documentation for more samples and chart types. http://code.google.com/apis/chart/interactive/docs/reference.html
Update: There's a simple way as pointed out by Scott Hemmeter in his comment below. Just use the sort() method and the first element in the list is the MAX or MIN based upon your sort (DESC or ASC). Thanks, Scott
This is just a way that i followed, not sure if LIST's have a pre-defined function to find out the maximum... If you do find a easier way, share it in the comments box below.
Here, "samplevalues" is a LIST of Decimal's
This is just a way that i followed, not sure if LIST's have a pre-defined function to find out the maximum... If you do find a easier way, share it in the comments box below.
Here, "samplevalues" is a LIST of Decimal's
List<Decimal> samplevalues = new List<Decimal>();
samplevalues.add(55.0);
samplevalues.add(75.5);
samplevalues.add(99.3);
Decimal maxvalue = samplevalues[0];
For (integer i =0;i<samplevalues.size();i++)
{
if( samplevalues[i] > maxvalue)
maxvalue = samplevalues[i];
}
system.debug('the max value is'+maxvalue);
Many thanks to Mr.Ranjeet Singh for submitting this article. This article is a sample code which lets you upload contacts from a Visualforce Page using a CSV file...
Click here if you too would like to submit an article for this blog
Step 1:
Click here if you too would like to submit an article for this blog
Step 1:
1) Create the Apex Class: UploadRecordUsingCSVContact
public with sharing class UploadRecordUsingCSVContact {
public Blob FileRecords{get;set;}
String[] LineNo=new String[]{};
List<Contact> AllContact;
Public Pagereference UploadFile()
{
String FileData=FileRecords.toString();
LineNo=FileData.split('\n');
Allcontact=new List<Contact>();
for(Integer i=1;i<LineNo.size();i++)
{
Contact con=new Contact();
String[] ActualData=new String[]{};
ActualData=LineNo[i].split(',');
con.FirstName=ActualData[0];
con.LastName=ActualData[1];
con.Email=ActualData[2];
con.Phone=ActualData[3];
Allcontact.add(con);
}
try
{
insert Allcontact;
}
catch(Exception e)
{
}
return Null;
}
Step 2: Create VF Page: UploadRecordUsingCSVContact
<apex:page controller="UploadRecordUsingCSVContact" >
<apex:form >
<apex:sectionHeader title="Upload Contact Records uing CSV File"/>
<apex:pageblock >
<Center>
<apex:inputfile value="{!FileRecords}"></apex:inputfile><apex:commandButton value="Upload File" action="{!UploadFile}"/><br/><br/>
<font color="Red"><b>Note: <a href="{!$Resource.ContactUploadTemplate}" target="__blank">Click Here </a>To download the Format.</b></font>
</Center>
</apex:pageblock>
</apex:form>
</apex:page>
Step 3: Create a CSV File and the file must be in the following mentioned Format:
First Name | Last Name | Phone | |
Ranjeet | Singh | xxxxx@gmail.com | xxxxxxx |
insufficient_access_on_cross_reference_entity
insufficient_access_on_ cross_reference_entity APEX / Salesforce
4:23 PM
NOTE: A common cause for this issue is the below scenario. Read on, if that's not the case for you.
*If you are trying to share "Record X" with "User Y" and "User Y" already has access to "Record X" this error happens.
Even though i understood what this means and have dealt with it earlier, this time this error message sucked my brain for one week. Finally, i got it sorted out and i hope this post helps someone understand and solve as well.
*If you are trying to share "Record X" with "User Y" and "User Y" already has access to "Record X" this error happens.
Even though i understood what this means and have dealt with it earlier, this time this error message sucked my brain for one week. Finally, i got it sorted out and i hope this post helps someone understand and solve as well.
When does this error happen?
This error normally happens when a DML operation is performed. Meaning that, whenever an Insert or Update is performed. You won't see this error when you save your APEX class or TRIGGER, because this error happens at RUNTIME.
What does this error mean?
This error means that you are trying to do an operation which is not supposed to be done, or the operation you are about to perform is not permitted according to the Sharing and Security settings defined. This error message does NOT always mean that you lack access to do the operation, even though it might be the case sometimes. So, even if you are an ADMINISTRATOR you may get this message.
Possible Causes:
Let's take some scenario's and analyze.
Scenario 1: Creating a new record (Account/Contact/...) and setting the Owner. Applies to updating records as well.
So, in your code you create some records. By Default the creator of the record is the Owner. You want to change this and you modify the OwnerId column of the newly created records. You make "User X" as the Owner. Now when you run the code, you get the Error below:
System.DmlException: Insert failed. First exception on row 2; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []
Things to check:
*Check that the running user (in this case you) has access to the object being operated. Check that he has CREATE privileges on the object. This is optional, but is always better to start from here.
*Check that the Owner ie User X has CREATE permission on the object. Check that his profile has the CREATE permission on the particular object. He might not be having it, grant him permission and the issue is resolved.
Scenario 2:
Creating or Updating an Opportunity (just for an example, might be any object). Setting the related Account of the Opportunity.
So, let's say that you create 5 Opportunities and you set the Owner to "User X". You set the Account to "Account X". When your code tries to insert these 5 opportunities, it fails and you get the same error message.
System.DmlException: Insert failed. First exception on row 2; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []
Reason:
This is because "User X" does not have access to "Account X". When you try to create an Opportunity for "Account X" that he does not have access to the code fails. Either grant access to "User X" for "Account X" manually or through code and then do the Insert.
Scenario 3:
The Sharing Object.
This is a bit complex to get at. atleast for me. You might be aware that every object has its own Share object. So, Account has AccountShare and Customobj__c has Customobj__Share
When you insert or update records in this object you might receive the same error message. There are a number of reasons for this to happen.
*If you are trying to share "Record X" with "User Y" and you yourself do not have access to "Record x", this error happens.
*If you are trying to share "Record X" with "User Y" and "User Y" does not have access to the object (the profile level permission, create read edit delete), this error happens.
*If you are trying to share "Record X" with "User Y" and "User Y" already has access to "Record X" this error happens.
SF Uploadify is a solution developed by Aslam Bari. Simply Cool and interesting.
Here is a small screencast of how the tool works - http://screencast.com/t/ibDqgMBbfQ
You can check his blog for more information about this tool in the links below:
http://techsahre.blogspot.com/2011/09/sf-uploadify-file-uploading-utility-for.html
http://www.aslambari.com/sf_uploadify.html
Here is a small screencast of how the tool works - http://screencast.com/t/ibDqgMBbfQ
You can check his blog for more information about this tool in the links below:
http://techsahre.blogspot.com/2011/09/sf-uploadify-file-uploading-utility-for.html
http://www.aslambari.com/sf_uploadify.html
As the title of the article implies, in this post we will be seeing an example which uses radio button in a table in visualforce and allows selecting one of the records in the table.
You can see a demo of the example here - Click here (forcetreedemos)
Visualforce Page:
Apex Class: RadioButton
You can see a demo of the example here - Click here (forcetreedemos)
Visualforce Page:
<apex:page controller="RadioButton" showheader="false">
<apex:form>
<apex:pageblock id="allcons" title="Available Contacts">
<apex:pageblocktable id="allcons" value="{!AllContacts}" var="allcon">
<apex:column headervalue="Set as Primary">
<apex:actionsupport action="{!selectcon}" event="onclick" rerender="consel,allcons">
<input type="radio" />
<apex:param name="conid" value="{!allcon.Id}">
</apex:param></apex:actionsupport>
</apex:column>
<apex:column headervalue="Last Name">
<apex:outputfield value="{!allcon.LastName}">
</apex:outputfield></apex:column>
<apex:column headervalue="First Name">
<apex:outputfield value="{!allcon.FirstName}">
</apex:outputfield></apex:column>
<apex:column headervalue="Email">
<apex:outputfield value="{!allcon.Email}">
</apex:outputfield></apex:column>
<apex:column headervalue="Phone">
<apex:outputfield value="{!allcon.Phone}">
</apex:outputfield></apex:column>
</apex:pageblocktable>
</apex:pageblock>
<apex:pageblock id="consel" title="Selected Contact">
<apex:pageblocktable id="allcons" value="{!selectedContact}" var="selcon">
<apex:column headervalue="Last Name">
<apex:outputfield value="{!selcon.LastName}">
</apex:outputfield></apex:column>
<apex:column headervalue="First Name">
<apex:outputfield value="{!selcon.FirstName}">
</apex:outputfield></apex:column>
<apex:column headervalue="Email">
<apex:outputfield value="{!selcon.Email}">
</apex:outputfield></apex:column>
<apex:column headervalue="Phone">
<apex:outputfield value="{!selcon.Phone}">
</apex:outputfield></apex:column>
</apex:pageblocktable>
</apex:pageblock>
</apex:form>
</apex:page>
Apex Class: RadioButton
public class RadioButton {
List<contact> selectcon;
Public List<contact> getAllContacts()
{
List<contact> allcons = [Select Id,FirstName,LastName,Email,Phone from Contact limit 5];
return allcons;
}
Public void selectcon()
{
String selcontactid = System.currentPagereference().getParameters().get('conid');
Contact con = [Select Id,FirstName,LastName,Email,Phone from Contact where Id=:selcontactid];
selectcon = new List<contact>();
selectcon.add(con);
}
Public List<contact> getselectedContact()
{
return selectcon;
}
}
This Winter 11, there is a new chatter component which allows you to embed chatter feeds in a Visualforce page.
Here is the official release notes and further details. Click here
Here is a sample visualforce page using this component. This page displays the feeds for the current logged in user.
Here is the official release notes and further details. Click here
Here is a sample visualforce page using this component. This page displays the feeds for the current logged in user.
<apex:page >
<chatter:feed entityId="{!$User.Id}"/>
</apex:page>
Note that the "entityID" attribute determines the feeds to be displayed. This can be a UserId, a custom or standard object record ID provided chatter is enabled for that object.
You may also create a Visualforce page with this component, and then create a home page sidebar component and embed the Visualforce page in the sidebar component.
A previous post describes how to pass paramters to a Visualforce page, and fetch the passed parameter values in your Apex Class(controller). Click here to read the post.
In this article we will see how to fetch the paramter value directly in your Visualforce page instead of getting it from the Apex Class(controller).
{!$CurrentPage.parameters.paramtername}
This global variable provides the capability.
Let's see a small visualforce example to see how it works.
In this article we will see how to fetch the paramter value directly in your Visualforce page instead of getting it from the Apex Class(controller).
{!$CurrentPage.parameters.paramtername}
This global variable provides the capability.
Let's see a small visualforce example to see how it works.
<apex:page>
The value of the paramter name passed to this page is :{!$CurrentPage.parameters.name}
</apex:page>
Save the above Visualforce page with the name "testpage".
Now, go to the URL bar and type the following address
http://yourinstance.salesforce.com/apex/testpage?name=Edwin
Your Visualforce page will display the output "
The value of the paramter name passed to this page is : Edwin
You can use the apex:param component when you want to pass paramters dynamically between visualforce pages, and the above method works as usual.
This is a step by step guide which takes you through getting started with using styles and CSS in your Visualforce Pages.
This sample code covers a general query utility which can be used to query any object.
This is the general class which runs the query. Comments are embedded inline for understanding the functionality.
Copy and paste this class
To Call this class:
You can call this class from any other class. Below is a sample code which you can embed into any class or you can execute this from the system log.
This is the general class which runs the query. Comments are embedded inline for understanding the functionality.
Copy and paste this class
Public class QueryUtility
{
// Function to run the query
Public List<sObject> runQuery(String objname,String[] fieldnames,String condition)
{
List<sObject> queryresult;
String fieldslist = '';
// Generate the fieldslist from the string array
if (fieldnames != NULL)
{
if(fieldnames.size() > 0)
{
for (Integer i=0; i < fieldnames.size(); i++)
{
if( i <= (fieldnames.size() - 2))
fieldslist = fieldslist+fieldnames[i]+',';
else
fieldslist = fieldslist+fieldnames[i];
}
}
}
// Construct the query string
String soqlquery = 'Select '+fieldslist+' from '+objname+' '+condition;
// Run the query
queryresult = Database.query(soqlquery);
return queryresult;
}
}
To Call this class:
You can call this class from any other class. Below is a sample code which you can embed into any class or you can execute this from the system log.
// Construct the list of fields
String[] flist = new List<String>{'Name','Id'};
// Initialte a new variable of the general utility class
QueryUtility test = new QueryUtility();
// Call the runquery method to execute the query. Note that the condition has to be passed as an empty string if you do not have any condition
Account[] qresult = test.runQuery('Account',flist,'');
system.debug('The query result is'+qresult);
This article covers a sample code to insert a poll component into your Salesforce.com instance as a home page component, or elsewhere Visualforce is supported.
This component allows administrators to open up a simple poll for users to get feedback from users. Once installed, the poll component can be configured easily.
Below is a demo of the application. Note that the below is an iframe of a Force.com Site page, Yes, it's a visualforce page embedded within this blog.
This component allows administrators to open up a simple poll for users to get feedback from users. Once installed, the poll component can be configured easily.
You can watch the demo at forcetreedemos too..
To install the app in your Salesforce instance, install the below package.
Production, Developer Org - https://login.salesforce.com/packaging/installPackage.apexp?p0=04t900000000sla
Sandbox - https://test.salesforce.com/packaging/installPackage.apexp?p0=04t900000000sla
Suggestions and Comments welcome!
salesforce test method
A Guide to writing Test Methods for an Apex Class in Salesforce - Part 2
3:36 PMThe Basic - Getting Started
Let's start by considering a simple apex class.
Now, we shall write the test method for this class.
Step 1: You have two options. You can have the test method in the same class above, OR you can have a separate class which has the test method for the above class. I always go with a separate class, because
Step 2: Save the class and click on the "Run Test" button as shown below.
Step 3: You will see the screen shown below.
As you can see, the test method coverage is 100%, meaning that all lines of the apex class have been covered.
Now, click on the "100" link highlighted in the "Code Coverage" section as shown above.
You will see the screen shown below..
A Blue color denotes - CODE COVERED
A RED color denotes - CODE NOT COVERED
Since our code coverage is 100% we do not have any red lines.
Let's start by considering a simple apex class.
Public class mysimpleclass { Public void samplemethod() { Integer a = 10; Integer b = a + 20; system.debug('The value of b is'+b); } }
Now, we shall write the test method for this class.
Step 1: You have two options. You can have the test method in the same class above, OR you can have a separate class which has the test method for the above class. I always go with a separate class, because
- It is easy to organize.
- Make use of @istest notation to prevent the test class from being counted against the organization apex code limit. Remeber, comments and classes with @istest notation are not counted.
Create a new apex class as below. Please note that this is the basic standard for any test class.
@istest
private class mysimpleclass_TestMethod // Name of the test class, Can be any name
{
static testmethod void mysimpleclass_TestMethod() // Name of the test method. Must be the same as the class name
{
mysimpleclass testcls = new mysimpleclass(); // Initialize variable for original class
testcls.samplemethod(); // Call Function of Original class
}
}
Step 2: Save the class and click on the "Run Test" button as shown below.
Step 3: You will see the screen shown below.
As you can see, the test method coverage is 100%, meaning that all lines of the apex class have been covered.
Now, click on the "100" link highlighted in the "Code Coverage" section as shown above.
You will see the screen shown below..
A RED color denotes - CODE NOT COVERED
Since our code coverage is 100% we do not have any red lines.
I have done this before and ran into the same problem again recently. Before I forget this again, let me write it down just in case there are people who think like me.
So, it was just one letter which cost me 1 to 2 hours of research.
To point your Blackberry Device or your Blackberry Simulator to the Sandbox, you will have to do the steps as outlined in this article by Salesforce. Click here
I did exactly (rather not), what was told there and i couldn't point by Blackberry to the Sandbox. After two hours i found out what was wrong.
I typed in, Izsand (ie, a Capital I ( a I as in Ice) and then zsand).
It should have been lzsand (ie, a small l as in lazy and then zsand).
Probably I should go back and learn alphabets properly.
So, it was just one letter which cost me 1 to 2 hours of research.
To point your Blackberry Device or your Blackberry Simulator to the Sandbox, you will have to do the steps as outlined in this article by Salesforce. Click here
I did exactly (rather not), what was told there and i couldn't point by Blackberry to the Sandbox. After two hours i found out what was wrong.
I typed in, Izsand (ie, a Capital I ( a I as in Ice) and then zsand).
It should have been lzsand (ie, a small l as in lazy and then zsand).
Probably I should go back and learn alphabets properly.
This article would cover steps to create a Visualforce Page which outputs a tree like structure wherein you could view Accounts, the Contacts related to the account and the Cases related to the Contact - All in one single tree structure.
Watch a DEMO here.....
Screenshot:
Step 1:
Download the Jquery Plugin from here. Upload this Zip file into Static Resources with the name "Jtreeview"
Step 2:
Create the Apex Class "treenodes" and paste the below code.
Step 3:
Create a Visualforce Page "TreeViewDemo" and paste the below code.
Note: You may modify the hierarchy by replacing the Objects and the queries with your required ones. Also, you may have to optimize the apex class to handle more than 100 queries as this demo has a SOQL query within a FOR loop (An Example of bad programming practice).
Watch a DEMO here.....
Screenshot:
Step 1:
Download the Jquery Plugin from here. Upload this Zip file into Static Resources with the name "Jtreeview"
Step 2:
Create the Apex Class "treenodes" and paste the below code.
public class treenodes { /* Wrapper class to contain the nodes and their children */ public class cNodes { public List<Contact> parent {get; set;} Public Account gparent {get;set;} public cNodes(Account gp, List<Contact> p) { parent = p; gparent = gp; } } /* end of Wrapper class */ Public List<cNodes> hierarchy; Public List<cNodes> getmainnodes() { hierarchy = new List<cNodes>(); List<Account> tempparent = [Select Id,Name from Account]; for (Integer i =0; i< tempparent.size() ; i++) { List<Contact> tempchildren = [Select Id,FirstName,LastName,(Select Id,CaseNumber,Subject from Cases) from Contact where AccountId = :tempparent[i].Id]; hierarchy.add(new cNodes(tempparent[i],tempchildren)); } return hierarchy; } }
Step 3:
Create a Visualforce Page "TreeViewDemo" and paste the below code.
<apex:page sidebar="false" controller="treenodes" showheader="false"> <!-- Include the Jquery Script files --> <link rel="stylesheet" href="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.treeview.css')}"/> <script src="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.js')}" type="text/javascript"></script> <script src="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.cookie.js')}" type="text/javascript"></script> <script src="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.treeview.js')}" type="text/javascript"></script> <!-- End of Javascript files --> <script type="text/javascript"> $(function() { $("#tree").treeview({ collapsed: false, animated: "medium", control:"#sidetreecontrol", persist: "location" }); }) </script> <br/> <br/> <br/> <!-- Tree --> <div class="treeheader" style="height:0px;"> </div> <div id="sidetreecontrol"><a href="?#"><font style="color:blue;">Collapse All</font></a> | <a href="?#"><font style="color:blue;">Expand All</font></a></div> <ul id="tree"> <apex:repeat value="{!mainnodes}" var="parent"> <li><strong><apex:outputtext style="color:blue;" escape="false" value="{!parent.gparent.Name}"/></strong> <ul> <apex:repeat value="{!parent.parent}" var="child"> <li><span class="formattextcon"><apex:outputtext style="color:green;" escape="false" value="{!child.LastName}"/></span> <ul> <apex:repeat value="{!child.Cases}" var="gchildren"> <li> <span class="formattextcon"> <apex:outputtext escape="false" style="color:red;" value="{!gchildren.CaseNumber}"/> <b>||</b> <apex:outputtext escape="false" value="{!gchildren.Subject}"/> </span> </li> </apex:repeat> </ul> </li> </apex:repeat> </ul> </li> </apex:repeat> </ul> <!-- End of Tree --> </apex:page>
Note: You may modify the hierarchy by replacing the Objects and the queries with your required ones. Also, you may have to optimize the apex class to handle more than 100 queries as this demo has a SOQL query within a FOR loop (An Example of bad programming practice).
I have put together a small application which helps log tickets, and track them. This application was specifically designed keeping in mind the way tickets/incidents are handled in a typical IT Service Desk.
This tool also has a timesheet feature, which logs the amount of work spent by each employee on each ticket.
Watch a working Demo of the tool here....@ forcetreedemos
Timesheet Management - Click here
Incident Management - Click here
Below are some of the screenshots from this tool. You can install the package from here.
To install to Production/Developer instance : https://login.salesforce.com/?startURL=%2Fpackaging%2FinstallPackage.apexp%3Fp0%3D04t900000000mDE
To install to your Sandbox: https://test.salesforce.com/?startURL=%2Fpackaging%2FinstallPackage.apexp%3Fp0%3D04t900000000mDE
Screenshots:
This tool also has a timesheet feature, which logs the amount of work spent by each employee on each ticket.
Watch a working Demo of the tool here....@ forcetreedemos
Timesheet Management - Click here
Incident Management - Click here
Below are some of the screenshots from this tool. You can install the package from here.
To install to Production/Developer instance : https://login.salesforce.com/?startURL=%2Fpackaging%2FinstallPackage.apexp%3Fp0%3D04t900000000mDE
To install to your Sandbox: https://test.salesforce.com/?startURL=%2Fpackaging%2FinstallPackage.apexp%3Fp0%3D04t900000000mDE
Screenshots:
While there is already an "Idea Under Construction" for a customizable homepage here, you may still want to look at the below application.
This excellent app has been developed by Kusiri and is called iSalesforce.
The source code can be downloaded from here. Here is the video from the app's code share page.
This excellent app has been developed by Kusiri and is called iSalesforce.
The source code can be downloaded from here. Here is the video from the app's code share page.
What if you wanted to display a dashboard in a Visualforce Page, or what if you do not like the standard dashboard's of Salesforce and wanted to create new dashboard's.
This article shows an example of displaying dashboard's in a Visualforce page using JQuery Flot.
JQuery Flot is an open source Jquery Plugin which can be downloaded from here.The link has proper documentation and the various ways of using Flot.
You can watch a demo in action here.
Screenshot:
Step 1:
Get the Jquery Flot ZIP file from here. Make sure that you download the latest version when available. This example was tested with Flot version 0.6.
Step 2:
Upload the ZIP file just downloaded into Static Resource. Let's Name the Static Resource "FlotDashboard". You may rename it to a meaningful name if you like to.
Step 3:
Let's create a Visualforce Page to see how the dashboard works.
Step 4:
Modify the script above to plot your own values in the dashboard. You can also compute your data points in an apex class and pass them to the dashboard.
I will try and post a more elaborate example of customizing this Dashboard using Apex.
This article shows an example of displaying dashboard's in a Visualforce page using JQuery Flot.
JQuery Flot is an open source Jquery Plugin which can be downloaded from here.The link has proper documentation and the various ways of using Flot.
You can watch a demo in action here.
Screenshot:
Step 1:
Get the Jquery Flot ZIP file from here. Make sure that you download the latest version when available. This example was tested with Flot version 0.6.
Step 2:
Upload the ZIP file just downloaded into Static Resource. Let's Name the Static Resource "FlotDashboard". You may rename it to a meaningful name if you like to.
Step 3:
Let's create a Visualforce Page to see how the dashboard works.
<apex:page showheader="false"> <html> <head> <title>Flot Examples</title> <link href="{!URLFOR($Resource.FlotDashboard,'flot/examples/layout.css')}" rel="stylesheet" type="text/css"></link> <!--[if IE]><script language="javascript" type="text/javascript" src="{!URLFOR($Resource.FlotDashboard,'flot/excanvas.min.js')}"></script><![endif]--> <script language="javascript" type="text/javascript" src="{!URLFOR($Resource.FlotDashboard,'flot/jquery.js')}"></script> <script language="javascript" type="text/javascript" src="{!URLFOR($Resource.FlotDashboard,'flot/jquery.flot.js')}"></script> <script language="javascript" type="text/javascript" src="{!URLFOR($Resource.FlotDashboard,'flot/jquery.flot.stack.js')}"></script> </head> <body> <h1>Flot Examples</h1> <div id="placeholder" style="width:600px;height:300px"></div> <p>One of the goals of Flot is to support user interactions. Try pointing and clicking on the points.</p> <p id="hoverdata">Mouse hovers at (<span id="x">0</span>, <span id="y">0</span>). <span id="clickdata"></span></p> <p>A tooltip is easy to build with a bit of jQuery code and the data returned from the plot.</p> <p><input id="enableTooltip" type="checkbox"/>Enable tooltip</p> <script id="source" language="javascript" type="text/javascript"> $(function () { var sin = [], cos = []; for (var i = 0; i < 14; i += 0.5) { sin.push([i, Math.sin(i)]); cos.push([i, Math.cos(i)]); } var plot = $.plot($("#placeholder"), [ { data: sin, label: "sin(x)"}, { data: cos, label: "cos(x)" } ], { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true, clickable: true }, yaxis: { min: -1.2, max: 1.2 } }); function showTooltip(x, y, contents) { $('<div id="tooltip">' + contents + '</div>').css( { position: 'absolute', display: 'none', top: y + 5, left: x + 5, border: '1px solid #fdd', padding: '2px', 'background-color': '#fee', opacity: 0.80 }).appendTo("body").fadeIn(200); } var previousPoint = null; $("#placeholder").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if ($("#enableTooltip:checked").length > 0) { if (item) { if (previousPoint != item.datapoint) { previousPoint = item.datapoint; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y); } } else { $("#tooltip").remove(); previousPoint = null; } } }); $("#placeholder").bind("plotclick", function (event, pos, item) { if (item) { $("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + "."); plot.highlight(item.series, item.datapoint); } }); }); </script> </body> </html> </apex:page>
Step 4:
Modify the script above to plot your own values in the dashboard. You can also compute your data points in an apex class and pass them to the dashboard.
I will try and post a more elaborate example of customizing this Dashboard using Apex.
This example illustrates the way to upload a file and attach it against any record using Visualforce. The file that you upload using this will be available in the "Notes & Attachments" related list for the record.
Click here if you are looking to upload a file into "Documents".
Step 1: Create an Apex class named "attachmentsample" . Paste the code below.
Step 2:
Create a Visualforce page named "attachment" and paste the code below.
Quick Test:
If you do not wish to do Step3 and 4 do this. Paste the following URL in your browser
http://yoursalesforceinstance.com/apex/attachment?id=0017000000eiDgy
ID should be a Valid Account Id of your instance.
Step 3:
Create a custom button (Detail Page button) on Account and select the new Visualforce page that you created as the source.
Step4:
Add the button created in Step3 to the Account Page layout.
You can test this by navigating to any account and clicking on the button that you created in Step3.
You may test
Click here if you are looking to upload a file into "Documents".
Step 1: Create an Apex class named "attachmentsample" . Paste the code below.
public class attachmentsample {
public attachmentsample(ApexPages.StandardController controller) {
}
Public Attachment myfile;
Public Attachment getmyfile()
{
myfile = new Attachment();
return myfile;
}
Public Pagereference Savedoc()
{
String accid = System.currentPagereference().getParameters().get('id');
Attachment a = new Attachment(parentId = accid, name=myfile.name, body = myfile.body);
/* insert the attachment */
insert a;
return NULL;
}
}
Step 2:
Create a Visualforce page named "attachment" and paste the code below.
<apex:page standardController="Account" extensions="attachmentsample">
<apex:form >
<apex:sectionHeader title="Upload a Attachment into Salesforce"/>
<apex:pageblock >
<apex:pageblocksection columns="1">
<apex:inputfile value="{!myfile.body}" filename="{!myfile.Name}" />
<apex:commandbutton value="Save" action="{!Savedoc}"/>
</apex:pageblocksection>
</apex:pageblock>
</apex:form>
</apex:page>
Quick Test:
If you do not wish to do Step3 and 4 do this. Paste the following URL in your browser
http://yoursalesforceinstance.com/apex/attachment?id=0017000000eiDgy
ID should be a Valid Account Id of your instance.
Step 3:
Create a custom button (Detail Page button) on Account and select the new Visualforce page that you created as the source.
Step4:
Add the button created in Step3 to the Account Page layout.
You can test this by navigating to any account and clicking on the button that you created in Step3.
You may test
Came across these excellent Ad's and the making of these Ad's.Watch and have fun!!!
The Making of these Ad's
The Making of these Ad's
You might be knowing that there is a field type called "Rich Text Field". This field allows you to format the text that you enter, add a URL, Insert pictures etc. It looks mostly like a big textbox with a editing toolbar at the top of the textbox. This is how a rich text field looks like.
The number of visible lines (the value that you specify while creating the field or editing it at Setup -> Object -> Field) controls the height of this field in a Visualforce Page. You may also use the style attribute to define your own height.
Rerender
Rich Text fields do not work with rerender. So, if you say that you have a button "Add another box", and clicking on this would rerender the panel and add one more rich text field, then this wont work. You will have to remove the "rerender" attribute and it works.
You should not have the "immediate=true" attribute as well on the commandbutton. This causes the value of the existing rich text fields to be lost.
So, if you have a button in a page which adds more "Rich Text Fields" or does some other rerendering, remove all the rerenderings and do a full page refresh. If you still face issues, remove the "immediate=true" attribute and try again.