Saturday, July 1, 2017

SOQL query in javascript example

You can use SOQL in java-script on your VF pages or any kind of java-script that you write, like we can get it executed on click of a button or link present on your detail page of a record. Below is the simple example and you can use it and modify it accordingly :

Javascript code:


{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}
try{
var query = "SELECT Id,Name from Account LIMIT 2";
var records = sforce.connection.query(query);
var records1 = records.getArray('records');
alert(records);
var accountNames = '';
for(var i=0;i<records1.length;i++){
accountNames = accountNames + records1[i].Name + ',';
}
alert(accountNames);
if(records1.length == 1){
//window.location.href = '<a href="http://www.google.com" rel="nofollow" title="Link added by VigLink" class="vglnk"><span>http</span><span>://</span><span>www</span><span>.</span><span>google</span><span>.</span><span>com</span></a>';
}
else{
alert('There is no Account');
}
}
catch(e){
alert('An Error has Occured. Error:' +e);
}

you need to use .js files that are in first two lines in order to use the api of salesforce to connect and fetch the records using SOQL. In the example you will see result of SOQL in alert statement. The result that is returned contains a ‘records’ named array component that can be used to iterate over and go through all the records and use it in the same manner as we do in usual apex program. For ex account.id, account.Name etc.


You can also use merge fields to create dynamic queries.

Similarly you can use javascript to create, update or delete the salesforce object’s records using API. Below is the sample code you can use to create a new account record in your org.


Javascript code:

try{
var accounts = [];
var account = new sforce.SObject("Account");
account.Name = "my new account Test";
accounts.push(account);
var results = sforce.connection.create(accounts);
if (results[0].getBoolean("success")) {
alert("new account created with id " + results[0].id);
} else {
alert("failed to create account " + results[0]);
}
}
catch(e){
alert('An Error has Occured. Error:' +e);
}


you just need to create a new button and fill the details as shown below in the screenshot:

SOQL in javascript example

Below this there would be a text box where you need to write your javascript code (provided above). After saving the button, you need to get it on your page layout and we are good to go.



What is Contact Role and Partner Role in salesforce?

What is Contact Role and Partner Role in salesforce?


Contact Roles:

A contact role defines the part that a contact or person account plays in a specific account, case, contract, or opportunity. For example, Tom Jones might be the Decision Maker for the opportunity, and Mary Smith might be the Evaluator. You can assign a contact role to any contact or person account that affects your account, case, contract, or opportunity. Contacts and person accounts can have different contact roles on various accounts, cases, contracts, or opportunities.

The Contact Roles related list of an account, case, contract, or opportunity displays the roles that each contact orperson account plays in that record. On person account detail pages, the Opportunity Contact Roles related list displays the opportunities on which the person account is listed in the Account Name field of the opportunity.
Partner Roles:
Partners are the companies with which you collaborate to close your sales deals. For each opportunity or account you create, the Partners related list allows you to store information about your partners and the roles they play in the opportunity or account. A partner must be an existing account within Salesforce.
If your organization has been enabled for partners, you can create partner accounts. Partner accounts arebusiness accounts that a channel manager uses to manage partner organizations, partner users, and activities. They are completely separate from account partnerships that are displayed in the Partners related list on an account. For more information about partner portals, see Partner Portal Overview.
We can find partners related list in
1. Account
2. Opportunity
Steps to implement Partner Roles:

1. Open an Account. Go to Partners related list and click "New" button.

2. Select Partners and their respective roles.


3. View the Partners.




How to call Apex class method from Javascript Custom Button?

In this post i am giving an example of how to call Apex Class method when ever we click on custom button. i this scenario i have one custom button that is created in my project custom object and place in details page layout.

Custom Button Code:

{!REQUIRESCRIPT(""/soap/ajax/18.0/connection.js"")} 
{!REQUIRESCRIPT(""/soap/ajax/18.0/apex.js"")} 

var id = sforce.apex.execute(""Projectctrl"",""createProject"",{easySupportId:""{!Support__c.Id}""});

location.reload();

Apex Class:

global class Projectctrl {
 webservice static Id createProject(String easySupportId){
  
  Support__c  supportobj=[select id,Category__c,OwnerId from Support__c where id=:easySupportId];
  
  SFDC_Project__c  projObj=new SFDC_Project__c();
  projObj.Easy_Support_No__c=supportobj.id;
  projObj.Road_Map_Identification__c='Enable';
  if(supportObj.Category__c=='Project')
   projObj.Request_Type__c='Project';
  else
   projObj.Request_Type__c='Minor Enhancement'; 
  projObj.Estimated_Monthly_Release__c=String.valueOf(System.today().month()+1);
  projObj.User_project_requested_by__c=supportObj.OwnerId;
  insert projObj;
  SFDC_Project__c sfdcProjectObj=[select Name from SFDC_Project__c where id=:projObj.Id];
  projObj.SFDC_Project_Name__c='Project-'+sfdcProjectObj.Name;
  update projObj;
  return projObj.id;
 }
}


Test class:

@isTest(seeAllData=true)
private class TestProjectctrl {

    static testMethod void myUnitTest() {
        // TO DO: implement unit test
        Support__c  supportobj=new Support__c();
        supportobj.Category__c='Project';
        supportobj.ContactName__c=UserInfo.getUserId();
        supportobj.Contact_No__c='9246263254';
        supportobj.Description__c='Test description';
        insert supportobj;
        Projectctrl.createProject(supportobj.id);
        
    }
    static testMethod void myUnitTest1() {
        // TO DO: implement unit test
        Support__c  supportobj=new Support__c();
        supportobj.Category__c='Others';
        supportobj.ContactName__c=UserInfo.getUserId();
        supportobj.Contact_No__c='9246263254';
        supportobj.Description__c='Test description';
        insert supportobj;
        Projectctrl.createProject(supportobj.id);
        
    }
}

Pass value from visualforce page to controller:

The first thing a apex programmer wants to know is: how do we communicate between visual force page and  controller. How to pass parameters from a visualforce page to a controller class ?

Lets develop a example that will capture a input in the visualforce page and pass the input value to the controller.


Visualforce Page:

<apex:page controller="passparamController">
    <!-- Pass parameters from visualforce page to controller -->
    <apex:form >
            <apex:pageblock >
                  Input Here <apex:inputText value="{!myinput}"/>
                 <apex:commandButton value="Submit" reRender="outputID" action="{!MyMethode}"/>
            </apex:pageblock>
            <apex:pageblock >
                 <b>Output here = </b><apex:outputText value="{!myoutput}" id="outputID">
                 </apex:outputText>
            </apex:pageblock>
    </apex:form>
</apex:page>


Controller

Public with sharing class passparamController {
  Public string myInput{get;set;}
  Public string myoutput{get;set;}
   
  Public void MyMethode(){
   myoutput = myInput ;
  }
}




In this example,
your {get;set} variable is binded to your input text box which makes it possible to get the value in the controller and also vice versa.

Thus when you press button the input value is passed on to controller.
<apex:inputText value="{!myinput}"/> your input text box is bind to the variable myinput string which is defined as get;set;

When the method is called from the submit button this value from myinput string is assigned to the myoutput string. This is proved when your input value is displayed in output section.

Note: Whenever we have any component wherein we want to input a value it is necessary that that component is enclosed between <apex:form>

salesforce validation in trigger

Salesforce provides validation rules in configuration for standard as well as custom objects. Validation rule for standard object can be written by navigating to following:
set up --> customize --> standard object name --> validation rule

similarly for custom object you can write validation rule by navigating to following:
set up --> create --> objects --> click on the custom object --> scroll down and click on new(next to validation Rules)

Although, you can write validation using simple configuration, sometimes your requirements may not be fullfilled using validation rule especially when your validation criteria is bit complex or need querying in database to check previously created data. In such a case you can write your logic in trigger.

Lets write down a very basic trigger that will throw a validation errror message.

Scenario : Show error message on account if annual revenue is less than 2000.

The error message can be shown using adderror method as shown in the example below:

trigger validation_using_Trigger on Account (before insert, before update) {
 for(Account acc:trigger.new){
    if(acc.AnnualRevenue < 2000){
       acc.adderror('Annual revenue cannot be less than 2000');
    }
 }
}


Above trigger will show error message at the top of the page. You can also display your message at a particular field, you only have to mention the field name in the adderror method as in the below example:

trigger validation_using_Trigger on Account (before insert, before update) {
 for(Account acc:trigger.new){
    if(acc.AnnualRevenue < 2000){
       acc.AnnualRevenue.adderror('Annual revenue cannot be less than 2000');
    }
 }
}

Above triggers will also throw validation errors while inserting/updating records using data loader.

While writing validation you have to make sure that your trigger is bulkified; that is you are properly iterating over for loop(trigger.new)

Also your trigger should run over before insert and before update contexts as you want the message be displayed before the record is created or updated.

Also the adderror method should always be written in the trigger new context. Trigger will not show error message if you are iterating over some other collection which is not trigger.new 

Data import from csv using Visualforce page

Data import from csv using Visualforce page 

Here is a example to read a csv file and display it in a pageblocktable.

Following example reads a csv file having account records in it and displays them in a table when "Read csv" button is pressed.

Csv file format used in this example:




Visualforce Page:

<apex:page controller="csvFileReaderController">
    <apex:form >  <!-- csv reader demo -->
        <apex:pageBlock >
            <apex:panelGrid columns="2" >
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Read csv" action="{!readcsvFile}"/>
            </apex:panelGrid>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!sObjectList}" var="rec">
              <apex:column value="{!rec.name}" />
              <apex:column value="{!rec.AccountNumber}" />
              <apex:column value="{!rec.Accountsource}" />
              <apex:column value="{!rec.Type}" />
              <apex:column value="{!rec.Website}" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>

Controller Class:

Public with sharing class csvFileReaderController {
public Blob csvFileBody{get;set;}
Public string csvAsString{get;set;}
Public String[] csvfilelines{get;set;}
Public String[] inputvalues{get;set;}
Public List<string> fieldList{get;set;}
Public List<account> sObjectList{get;set;}
  public csvFileReaderController(){
    csvfilelines = new String[]{};
    fieldList = New List<string>();
    sObjectList = New List<sObject>();
  }

  Public void readcsvFile(){
       csvAsString = csvFileBody.toString();
       csvfilelines = csvAsString.split('\n');
       inputvalues = new String[]{};
       for(string st:csvfilelines[0].split(','))
           fieldList.add(st);  
       
       for(Integer i=1;i<csvfilelines.size();i++){
           Account accRec = new Account() ;
           string[] csvRecordData = csvfilelines[i].split(',');
           accRec.name = csvRecordData[0] ;            
           accRec.accountnumber = csvRecordData[1];
           accRec.Type = csvRecordData[2];
           accRec.website = csvRecordData[3];
           accRec.AccountSource = csvRecordData[4];                                                                              
           sObjectList.add(accRec);  
       }
  }
}

Output :


Custom clone button in salesforce

Custom clone button in salesforce 

Salesforce provides Clone functionality for some standard objects(Standard Clone button),
However some standard objects do not have this button. For this purpose of cloning we will need to create custom button that will perform the functionality of cloning.
EX:Account

This cloning functionality can be achieved by writing a javascript for this custom button.

As an example lets create a custom button "Clone" on account that will clone the record.

Simply override your custom button "Clone" with the following java script and you will have your custom Clone button that functions exactly like standard clone button

{!REQUIRESCRIPT("/soap/ajax/22.0/connection.js")} 
window.parent.location.href="/{!Account.Id}/e?&deepclone=1&retURL=/{!Account.Id}";

retUrl specifies the location where you want to be on press of back button.