Progress bar for custom button

Progress bar for custom button on click salesforce

{!REQUIRESCRIPT("/soap/ajax/36.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/36.0/apex.js")} 
var CaseId = '{!Case.Id}'; 
var sta= '{!Case.status}'; 
if(sta){ 
var result=sforce.apex.execute("ApexClassName","Method",{CaseId:CaseId}); 

var overlay = document.createElement('overlay'); 
overlay.style.background = '#000'; 
overlay.style.position = 'absolute'; 
overlay.style.top='0px'; 
overlay.style.bottom = '0px'; 
overlay.style.right = '0px'; 
overlay.style.left = '0px'; 
overlay.style.zIndex = '1000'; 
overlay.style.opacity='0.7'; 

var loading = document.createElement('img'); 
loading.src = 'https://c.na5050.content.force.com/servlet/servlet.ImageServer?id=014446000001yJpw&oid=00De2323340uNx0'; 
loading.style.position = 'absolute'; 
loading.style.top='50%'; 
loading.style.left = '50%'; 
loading.style.zIndex = '1000'; 

overlay.appendChild(loading); 
document.body.appendChild(overlay); 

if(result!=null && result!='success'){ 

document.body.removeChild(overlay); 
var outerdiv = document.createElement('div'); 
outerdiv.innerHTML = result; 
outerdiv.style.display = 'inline-block'; 
outerdiv.style.fontSize ='14px'; 
outerdiv.style.color = 'red'; 
//outerdiv.style.border = '1px solid grey'; 
outerdiv.style.padding = '10px'; 


var mainDiv = document.createElement('div'); 
mainDiv.style.marginLeft = '30%'; 
mainDiv.style.marginTop = '10px'; 
mainDiv.appendChild(outerdiv); 

document.getElementById('errorDiv_ep').innerHTML = result; 
document.getElementById('errorDiv_ep').style.display=''; 
setTimeout(function(){ 
document.getElementById('errorDiv_ep').innerHTML = ''; 
document.getElementById('errorDiv_ep').style.display='none'; 
},5000); 


}else{ 
document.location.reload(true); 

}else{ 
alert('You can not revert back the case to Queue.'); 
document.getElementById('errorDiv_ep').innerHTML = 'You can not close the case.'; 
document.getElementById('errorDiv_ep').style.display=''; 
setTimeout(function(){ 
document.getElementById('errorDiv_ep').innerHTML = ''; 
document.getElementById('errorDiv_ep').style.display='none'; 
},5000); 
}

Custom Buttons in Service Cloud Console

Custom Buttons  in Service Cloud Console


{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")} 
{!REQUIRESCRIPT('/soap/ajax/35.0/apex.js')} 
{!REQUIRESCRIPT("/support/console/28.0/integration.js")}
//identify the id 
var c = new sforce.SObject("case"); 
c.id = "{!Case.Id}"; 
var Cstatus= "{!Case.Status}"; 
var resultOk = confirm("Are you sure,you want to clone the case"); 
if(resultOk){ 
var result = sforce.apex.execute("Casecloningfrombutton","cloneCaseList",{caseIds:"{!Case.Id}"}); 
alert(result);
if(result!=null){ 
var redirectUrl = '/'+result;
if (sforce.console.isInConsole()) {
sforce.console.getEnclosingTabId(function(enclosingResult){
sforce.console.getEnclosingPrimaryTabId(function(primaryResult){
sforce.console.openSubtab(primaryResult.id, redirectUrl, true, '', null);
});
});
}else{
window.location.href = redirectUrl;
}
}else{ 
alert('Insert failed - please contact with system admin'); 
}

how to display a table with dynamic columns in vf page

how to display a table with dynamic columns in vf page

<apex:pageBlock id="block">
    <apex:pageBlockTable id="table" var="exhlst" value="{!exhibitorList}">
    <tr>
        <td styleClass="freeze_horizontal">
        
        <b><apex:outputField value="{!exhlst.Name}" styleClass="freeze_horizontal"/></b>
        
        </td>
        <td>
            <apex:repeat value="{!$ObjectType.Exhibitor_Authenticity__c.FieldSets.NationalitiesName}" var="c">
              <apex:column headerValue="{!$ObjectType.Exhibitor_Authenticity__c.fields[c].Label}">
              <div style="background-color:{!If(exhlst[c]== 'Authentic','#b3ffb3',If(exhlst[c]== 'Remaining','#ffd480','#ff9999'))};">    
                    <apex:outputField value="{!exhlst[c]}"></apex:outputField>
               </div>
            </apex:column>
            </apex:repeat>
        </td>
    </tr>
   </apex:pageBlockTable>
</apex:pageBlock>

Apex Fieldset - getfieldpath in salesforce

use get method to iterate the fieldset value.

public static List<Schema.FieldSetMember> getFields(){
return SObjectType.Account.FieldSets.ExhibitorAuthenticity.getFields();
}

 for(Account itr:exhibitorAuthList){
                for(Schema.FieldSetMember f : getFields()){
                    if(itr.get(f.getFieldPath())=='Apple'){
                        exhibitorAuth.add('Apple');
                    }else if(itr.get(f.getFieldPath())=='Banana'){
                        exhibitorRemaining.add('Banana');
                    } 
                }
            }

    system.debug('API Name ====>' + fieldSetMemberObj.getFieldPath()); //api name
    system.debug('Label ====>' + fieldSetMemberObj.getLabel());
    system.debug('Required ====>' + fieldSetMemberObj.getRequired());
    system.debug('DbRequired ====>' + fieldSetMemberObj.getDbRequired());
    system.debug('Type ====>' + fieldSetMemberObj.getType());

Apex Map with comma separate value

Apex Iterate the map value and separate with comma

if(Trigger.isUpdate && Trigger.isAfter){
        Map<string,string> caseshopID = new Map<string,string>(); 
        for(case itr:trigger.new){
            if(itr.Case_Record_Type__c=='Additional Visa/GVAC' && itr.AdditionalQuotaRequest__c){
                caseshopID.put(itr.id,itr.Shop__c+','+itr.Additional_Quota__c);
            }
        }
        if(caseshopID.size()>0){
            caseglobalHelperClass.updateShopQuota(caseshopID);
        }
    }


public static void updateShopQuota(Map<string,string> caseshopid){

        set<string> shopID = new set<string>();
        Map<string,string> mapQuotaNum = new Map<string,string>();
        for(string a:caseshopid.values()){
            List<string> b=a.split(',');
            string c = string.join(b,',');
            List<String> d= c.split(',');
            system.debug('-------'+d[0]+'-----'+d[1]);
            shopID.add(d[0]);
            mapQuotaNum.put(d[0],d[1]);
        }
     
        List<Shop__c> updateshpList = [select id,IncreasedQuota__c from Shop__c where id IN:shopID];
        for(Shop__c itr:updateshpList){
           itr.IncreasedQuota__c  = Integer.valueof(mapQuotaNum.get(itr.Id));
        }
     
        if(updateshpList.size()>0){
            update updateshpList;
        }
    }

FieldSet in Apex

FieldSet in Apex


List<Schema.FieldSetMember> fieldSetMemberList =  Util.readFieldSetMethod('Case_FieldSet','Case');
for(Schema.FieldSetMember fieldSetMemberObj : fieldSetMemberList){
    system.debug('API Name ====>' + fieldSetMemberObj.getFieldPath()); //api name
    system.debug('Label ====>' + fieldSetMemberObj.getLabel());
    system.debug('Required ====>' + fieldSetMemberObj.getRequired());
    system.debug('DbRequired ====>' + fieldSetMemberObj.getDbRequired());
    system.debug('Type ====>' + fieldSetMemberObj.getType());   //type - STRING,PICKLIST
}

public static List<Schema.FieldSetMember> readFieldSetMethod(String fieldSetName, String ObjectName){
    Map<String, Schema.SObjectType> GlobalDescribeMap = Schema.getGlobalDescribe();
    Schema.SObjectType SObjectTypeObj = GlobalDescribeMap.get(ObjectName);
    Schema.DescribeSObjectResult DescribeSObjectResultObj = SObjectTypeObj.getDescribe();

    //system.debug('====>' + DescribeSObjectResultObj.FieldSets.getMap().get(fieldSetName));

    Schema.FieldSet fieldSetObj = DescribeSObjectResultObj.FieldSets.getMap().get(fieldSetName);

    //List<Schema.FieldSetMember> fieldSetMemberList =  fieldSetObj.getFields();
    //system.debug('fieldSetMemberList ====>' + fieldSetMemberList); 
    return fieldSetObj.getFields();
}  

@Test Visible Example

@Test Visible - Example

public class TestVisibleExample {
    // Private member variable
    @TestVisible private static Integer recordNumber = 1;

    // Private method
    @TestVisible private static void updateRecord(String name) {
        // Do something
    }
}


@isTest
private class TestVisibleExampleTest {
    @isTest static void test1() {
        // Access private variable annotated with TestVisible
        Integer i = TestVisibleExample.recordNumber;
        System.assertEquals(1, i);

        // Access private method annotated with TestVisible
        TestVisibleExample.updateRecord('RecordName');
        // Perform some verification
    }
}

SOQL on Salesforce Approval Process

ProcessInstance

SELECT Id, (SELECT Id, ProcessInstanceId, StepStatus, Comments, CreatedDate FROM Steps ORDER BY CreatedDate DESC)TargetObjectId, Status FROM ProcessInstance WHERE TargetObjectId='5009E000007vqVS'

ProcessInstanceStep

SELECT ActorId, Comments, CreatedById, CreatedDate, ElapsedTimeInDays, ElapsedTimeInHours, ElapsedTimeInMinutes, Id, OriginalActorId, ProcessInstanceId, StepNodeId, StepStatus, SystemModstamp FROM ProcessInstanceStep where ProcessInstanceId='04g9E000000P7ysQAC'


ProcessInstance with Step Name

SELECT Id, Name, ProcessDefinitionId FROM ProcessNode WHERE ProcessDefinitionId IN (SELECT ProcessDefinitionID FROM ProcessInstance WHERE TargetObjectId = '5009E000007vqTH')


Visualforce Bar Charts and Pie Chart

Visualforce Bar Charts and Pie Chart.

please find the more information on:

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_charting_appearance_bar_charts.htm

Visualforce page code:

<apex:page standardController="Account" extensions="ShowAccountPieChart">
    <apex:chart height="250" width="350" data="{!pieData}">
        <apex:pieSeries dataField="data" labelField="name"/>
        <apex:legend position="right"/>
    </apex:chart>
     <apex:outputPanel>
        <apex:pageblock title="Business Category Total Allowance" >
        <apex:chart height="250" width="600" data="{!pieData}">
            <apex:axis type="Numeric" position="left" fields="data" title="Allowed Visa"/> 
            <apex:axis type="Category" position="bottom" fields="name" title="Utilized Visa"/>         
            <apex:barSeries orientation="vertical" axis="left" xField="name" yField="data"/>
        </apex:chart>
    </apex:pageblock> 
    </apex:outputPanel>
</apex:page>

Apex controller:

public class ShowAccountPieChart{
 
    public ShowAccountPieChart(ApexPages.StandardController controller){
    //
    }
    public List<PieWedgeData> getPieData() {
        List<PieWedgeData> data = new List<PieWedgeData>();
        List<Account> memb = new List<Account>();
     
        //string accId = ApexPages.currentPage().getParameters().get('pv0');
        string accId = 'xxxx';
        string sql = 'SELECT Name,AllowedExhbitorsRollUp__c,Number_of_Visas_Utilised__c,Number_of_Cleaners_Utilised__c,Number_of_Maintenance_Staff_Utilised__c,IdCardRollUp__c,twpRollUp__c,FestivalVisaRollUp__c FROM Account where ID =:accId';
        memb = Database.Query(sql);
        for(Account a:memb){
            //data.add(new PieWedgeData('Allowance',Integer.valueof(a.AllowedExhbitorsRollUp__c)));
            data.add(new PieWedgeData('Visa Utilised',Integer.valueof(a.AllowedExhbitorsRollUp__c)/Integer.valueof(a.Number_of_Visas_Utilised__c)*10));
            data.add(new PieWedgeData('Cleaners Utilised',Integer.valueof(a.AllowedExhbitorsRollUp__c)/Integer.valueof(a.Number_of_Cleaners_Utilised__c)*10));
            data.add(new PieWedgeData('Maintenance Staff',Integer.valueof(a.AllowedExhbitorsRollUp__c)/Integer.valueof(a.Number_of_Maintenance_Staff_Utilised__c)*10));
            data.add(new PieWedgeData('GVAC',Integer.valueof(a.AllowedExhbitorsRollUp__c)/Integer.valueof(a.IdCardRollUp__c)*10));
            data.add(new PieWedgeData('Roll up',Integer.valueof(a.AllowedExhbitorsRollUp__c)/Integer.valueof(a.twpRollUp__c)*10));
            data.add(new PieWedgeData('Festival visa',Integer.valueof(a.AllowedExhbitorsRollUp__c)/Integer.valueof(a.FestivalVisaRollUp__c)*10));
        }
        /*
        data.add(new PieWedgeData('Jan', 30));
        data.add(new PieWedgeData('Jan', 30));
        data.add(new PieWedgeData('Feb', 15));
        data.add(new PieWedgeData('Mar', 10));
        data.add(new PieWedgeData('Apr', 20));
        data.add(new PieWedgeData('May', 20));
        data.add(new PieWedgeData('Jun', 5));
        */
        return data;
    }

    // Wrapper class
    public class PieWedgeData {

        public String name { get; set; }
        public Integer data { get; set; }

        public PieWedgeData(String name, Integer data) {
            this.name = name;
            this.data = data;
        }
    }
}


Javascript to validate minimum legth

Javascript to validate minimum legth

The below code will allow only two character

onkeypress="this.value= this.value.replace(/[^0-9]/g, '');return limitKeypress(event,this.value,2)"

function limitKeypress(event, value, maxLength) {
    if (value != undefined && value.toString().length >= maxLength) {
        event.preventDefault();
    }
}

Pass Variable from Apex controller to Javascript

Pass Variable from Apex controller to Javascript


1.Define the Javascript
           var serviceFeesDict = {};
           
 2.use ready fucntion to load the variable when page get loaded.         
            $(document).ready(function() {
           
                    <apex:repeat value="{!serviceFeesList}" var="serviceFee">
                        serviceFeesDict['{!serviceFee.Name}'] = {!serviceFee.Fee__c};
                    </apex:repeat>
              } 
3.use the Apex repeat var to iterate the value in JS.

               var feesValue = 0;
                if(isAA){
                    feesValue += serviceFeesDict['AA'];
                }
                if (isBB){
                    feesValue += serviceFeesDict['BB'];
                }

Salesforce AppExchange products

Salesforce AppExchange products

1. Document Creation and Automation: DrawLoop vs. Conga Merge--DrawLoop (willing to do custom work for free and had a more friendly administrative UI).

2. e-Signature: DocuSign vs. EchoSign--DocuSign (supported and was willing to help us with our non-SF API contracts and configuration; best contract app for any real estate industries; supports the red-line process). EchoSign was very arrogant and unhelpful when it came to special requests. They also tried to make you feel stupid for selecting another vendor. Plus, functionality (API integrations and red-line process was not supported).

3. Marketing Automation: Genius vs. Marketo--Genius (more friendly UI; all data stays in SFDC--one database; better price point; better customer support; supposed to release an open API in July/August of 2011). Marketo was a tad more complex to configure and the data was pushed and pulled from 2 databases.

4. Lead Generation: Jigsaw vs. NetProspex vs. InsideView vs. Hoovers--Jigsaw (no brainer! Jigsaw was bought by SF and they reconcile the Jigsaw contact database against all of the SFDC customers that buy it and opt for the shared licensing methodology--well, now it has been rolled into data.com). We ran accuracy tests against the other vendors, and they all had a 27% or less accuracy rate.

5. Cleansing/de-duping/normalizing data: CRM Fusion/DemandTools 2.0 vs. RingLead--CRM Fusion no contest! This is by far my favorite and most leveraged installed app. This makes mass updates, exports, new record inserts, mass record deletions, data querying a breeze. They don't use a push/pull/import/export model; the application pulls the data straight out of SFDC. There is an awesome feature that is in beta testing right now--instead of exporting the grid data, manipulating it in Excel, and uploading the new file into Mass Effect to upsert/update the data, they are putting all the functionality of an Excel spreadsheet into the application; so, you can manipulate the data (copy/paste, change values) inside the DemandTools application and click update and it pushes all of the changes straight into SFDC. I'm super stoked for this release!

6. Dialer: PowerDialer vs. Interactive Intelligence vs. Refractive Dialer--PowerDialer by InsideVieew (not a predictive dialer so there is no dead air, reps can generate their own call lists, context/content for the list (doesn't have to be sales based), record multiple VM's and select which VM they want to leave, real-time call dispositioning and activity logging, and perform actions when the call connects with the customer--send emails, content, etc.).

Visualforce page Model box onmouse over or onclick

Visualforce page Model box onmouse over or onclick


<a target="_self" href="/XXX/servlet/servlet.FileDownload?file={!caseAttachment.Attachment_Id__c}" download="{!caseAttachment.attachment_File_Name__c}" onmouseover="showDialog(this,'some message');"> <i class="fa fa-eye" style="float: left;margin-left: 30px;color: #61c027;font-size:24px;" ></i> </a>

<script>
//If you are using string literals, be sure to escape your double quotes!
function showDialog(urlval, message, width, largerText) {
    //set up the vars
var urlval = urlval;
//alert(urlval);
    var dialogTitle = 'Attachment',
        //dialogHTML = message,
dialogHTML = '<iframe src="'+urlval+'" width="420" height="315" frameborder="0" allowfullscreen></iframe>',
        dialogWidth,
        modalBlocker = document.createElement("div"),
        modalBox = document.createElement("div"),
        modalBoxInner = document.createElement("div"),
        modalBoxTitle = document.createElement("h3"),
        modalBoxClose = document.createElement("span");

    if (width) {
        dialogWidth = width;
    }
    else {
        dialogWidth = '500';
    }

    //debug info
    //console.log('title', title);
    //console.log('message', message);
    //console.log('width', width);
    //console.log('largerText', largerText);

 

    //Get the document size
    var w = 0; var h = 0;
    if (!window.innerWidth) {
        if (!(document.documentElement.clientWidth == 0)) {
            w = document.documentElement.clientWidth;
            h = document.documentElement.clientHeight;
        } else {
            w = document.body.clientWidth;
            h = document.body.clientHeight;
        }
    } else {
        w = window.innerWidth;
        h = window.innerHeight;
    }

    //Set up the modal blocker
    modalBlocker.setAttribute('Id', '__modalBlocker');
    modalBlocker.style.width = w + 'px';
    modalBlocker.style.height = document.body.scrollHeight + 'px';
    modalBlocker.style.position = 'absolute';
    modalBlocker.style.zIndex = '20000';
    modalBlocker.style.opacity = '.5';
    modalBlocker.style.filter = 'alpha(opacity=50)';
    modalBlocker.style.backgroundColor = '#000';
    modalBlocker.style.top = 0;
    modalBlocker.style.left = 0;

    //set up the modal box...
    modalBox.setAttribute('id', '__modalBox');
    modalBox.style.backgroundColor = '#fff';
    modalBox.style.width = dialogWidth + 'px';
    modalBox.style.zIndex = '20001';
    modalBox.style.position = 'fixed';
    modalBox.style.top = '200px';
    modalBox.style.left = ((w / 2) - (dialogWidth / 2)) + 'px';
    modalBox.style.borderRadius = '4px';
    modalBox.style.boxShadow = '1px 1px 10px #000';

    //...and the inner div
    modalBoxInner.style.position = 'relative';
    modalBoxInner.style.padding = '20px';
    if (largerText) modalBoxInner.style.fontSize = '1.6em';
    modalBoxInner.innerHTML = dialogHTML;


    //set up the close button
    modalBoxClose.innerHTML = 'X';
    modalBoxClose.title = 'Close';
    modalBoxClose.style.fontSize = '12px';
    modalBoxClose.style.backgroundColor = 'rgb(224, 7, 7)';
    modalBoxClose.style.color = '#fff';
    modalBoxClose.style.position = 'absolute';
    modalBoxClose.style.top = '0';
    modalBoxClose.style.right = '10px';
    modalBoxClose.style.display = 'block';
    modalBoxClose.style.width = '26px';
    modalBoxClose.style.padding = '5px';
    modalBoxClose.style.textAlign = 'center';
    modalBoxClose.style.cursor = 'pointer';
    modalBoxClose.style.borderBottomLeftRadius = '4px';
    modalBoxClose.style.borderBottomRightRadius = '4px';
    modalBoxClose.setAttribute('onclick', 'document.body.removeChild(document.getElementById(\'__modalBlocker\'));document.body.removeChild(document.getElementById(\'__modalBox\'));');

    //set up the dialog box title
    modalBoxTitle.innerHTML = dialogTitle;
    modalBoxTitle.style.display = 'block';
    modalBoxTitle.style.fontSize = '1.6em';
    modalBoxTitle.style.color = '#1797c0';
    modalBoxTitle.style.margin = '8px 0 0 8px';

    //Add the close button and the title to the modal box
    modalBox.appendChild(modalBoxClose);
    modalBox.appendChild(modalBoxTitle);
    modalBox.appendChild(modalBoxInner);

    //finally, add the modal box and the modal blocker to the page
    document.body.appendChild(modalBlocker);
    document.body.appendChild(modalBox);
}

<script>
Output


Apex variable to Display the value and change the css

Visualforce Page:

apex variable to Display the value and change the css .

<style>

.un_rvw{ color.green}
.incp {color.green}
</style>

<td style="text-align:left;">

<apex:outputPanel rendered="{!Case.Status != null}">

<apex:variable var="casePublicStatus" value="{!IF(Case.Status = 'Approved', 'Approved', IF(Case.Status = 'Rejected', 'Rejected', IF(Case.Status = 'Cancelled', 'Cancelled', IF(Case.Status = 'Application Complete', 'Completed', IF(Case.Status = 'Exit Confirmed', 'Exited', IF(Case.Status = 'Final Rejection' || Case.Status = 'Rejected' || Case.Status = 'Rejected by Immigration' || Case.Status = 'Rejected by Immigration 1' || Case.Status = 'Rejected by Immigration 2' || Case.Status =  'Rejected by Typing Dept' || Case.Status = 'Refund Issued', 'Rejected','In Process'))))))}"/>
<apex:variable var="casePStatus" value="{!Case.Public_Status_WF__c}"/>

<apex:variable var="caseCSS" value="{!IF(casePStatus= 'Approved', 'aprv',IF(casePStatus= 'Cancelled' || casePStatus= 'Rejected' || casePStatus= 'Warning', 'rjct', IF(casePStatus= 'Completed' || casePStatus= 'Exited', 'aprv',  IF(casePStatus= 'Pending Payment', 'pend',  IF(CONTAINS(casePStatus, 'Incomplete'), 'incp', 'un_rvw')))))}" />

<span class="sts {!caseCSS}" style="margin-left:-8px;">{!casePStatus}</span>

</apex:outputPanel>
</td>

Change Set

What is Change Set?
Change Set is the deployment tool by which Sales force Developer/Administrator can upload/deploy the changes to Sandbox (Test Environment) to Production. You can go in Setup>Deploy>Select any option of deployment. You can deploy changes in between Sandbox to Sandbox also.
There are three main topics and steps to understand first before deployment:
1. Outbound Change set:
This is first step to the deployment through Change set. Outbound change set is nothing but creation of connection or select the changes you done in Sandbox like Object, Custom Fields, Validation, Workflow, Classes, Trigger etc. For that you have to follow below steps.
· Login in to Sandbox account of Salesforce.com.
· Go to Setup>Deploy>Outbound Change set: It will show you information on Change set and Outbound/Inbound change set information.
· Press Continue button on this page.
· Click on New button and create the outbound change set. Enter the Name of outbound change set and description of this and Click on Save.
· Once you get outbound change set detail page click Add button on Change Set Components.
· This page will show you Component Type (App, Analytical Snapshot, Apex Class, Apex Sharing Reason, Apex Trigger, Button or Link, Custom Fields, Custom Label, Object, Report Type, Custom Setting, Dashboard, Document, Email Template, Field Set, Folder, Home page Component etc.) Select any of above part and Click on Add To Change Set Button.
· After above step you will get the list of components added on change set component section.
· You can view or add dependencies in this section.
· Click on Add Profile in Profile Setting for included components means you can ass profile your can see or share the changes whatever you have done.
· After completing above steps click on Upload button. This will do the actual deployment to the Production/other Sandbox.
· Select any option from given list of Sandbox and Production.
· Click on Upload button to selected environment.
· After above step you will get Completion Email on your given email id. Means you have successfully uploaded the outbound change set.

2. Deployment Connection:
This connection step will automatically created by Sales force. Which is allows the customization to be copied from one organization to another organization. Your should be login in Production to check above list.

3. Inbound Change Set:
Inbound change set is automatically created once outbound change set it created inbound change set gets the all changes sent by outbound change set.
· Select on inbound change set and get detail of outbound.
· You can view change set components list and deployment history.
· Click on validate it will show validation history in deployment History.
· Click on Deployment after successful validation and can see Deployment History.

Salesforce Apex Trigger

What Is Trigger?

Apex can be invoked through the use of triggers. A trigger is Apex code that executes before or after the following types of operations:
  • insert
  • update
  • delete
  • merge
  • upsert
  • undelete
Trigger and  Recovered Records:

The after undelete trigger event only works with recovered records—that is, records that were deleted and then recovered from the Recycle Binthrough the undelete DML statement. These are also called undeleted records.
The after undelete trigger events only run on top-level objects. For example, if you delete an Account, an Opportunity may also be deleted. When you recover the Account from the Recycle Bin, the Opportunity is also recovered. If there is an after undelete trigger event associated with both the Account and the Opportunity, only the Account after undelete trigger event executes.
The after undelete trigger event only fires for the following objects:
  • Account
  • Asset
  • Campaign
  • Case
  • Contact
  • ContentDocument
  • Contract
  • Custom objects
  • Event
  • Lead
  • Opportunity
  • Product
  • Solution
  • Task
Merger Trigger:
Merge events do not fire their own trigger events. Instead, they fire delete and update events as follows:
Deletion of losing records
A single merge operation fires a single delete event for all records that are deleted in the merge. To determine which records were deleted as a result of a merge operation use the MasterRecordId field in Trigger.old. When a record is deleted after losing a merge operation, itsMasterRecordId field is set to the ID of the winning record. The MasterRecordId field is only set in after delete trigger events. If your application requires special handling for deleted records that occur as a result of a merge, you need to use the after delete trigger event.
Update of the winning record
A single merge operation fires a single update event for the winning record only. Any child records that are reparented as a result of the merge operation do not fire triggers.
For example, if two contacts are merged, only the delete and update contact triggers fire. No triggers for records related to the contacts, such as accounts or opportunities, fire.
The following is the order of events when a merge occurs:
  1. The before delete trigger fires.
  2. The system deletes the necessary records due to the merge, assigns new parent records to the child records, and sets the MasterRecordId field on the deleted records.
  3. The after delete trigger fires.
The system does the specific updates required for the master record. Normal update triggers apply.
Trigger Context Variable:
VariableUsage
isExecutingReturns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
isInsertReturns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
isUpdateReturns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
isDeleteReturns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
isBeforeReturns true if this trigger was fired before any record was saved.
isAfterReturns true if this trigger was fired after all records were saved.
isUndeleteReturns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or theAPI.)
newReturns a list of the new versions of the sObject records.
Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers.
newMapA map of IDs to the new versions of the sObject records.
Note that this map is only available in before updateafter insert, and after update triggers.
oldReturns a list of the old versions of the sObject records.
Note that this sObject list is only available in update and delete triggers.
oldMapA map of IDs to the old versions of the sObject records.
Note that this map is only available in update and delete triggers.
sizeThe total number of records in a trigger invocation, both old and new.
Example:

Trigger t on Account (after insert) {

    for (Account a : Trigger.new) {
        // Iterate over each sObject
    }

    // This single query finds every contact that is associated with any of the
    // triggering accounts. Note that although Trigger.new is a collection of  
    // records, when used as a bind variable in a SOQL query, Apex automatically
    // transforms the list of records into a list of corresponding Ids.
    Contact[] cons = [SELECT LastName FROM Contact
                      WHERE AccountId IN :Trigger.new];
}
Be aware of the following considerations for trigger context variables:
  • trigger.new and trigger.old cannot be used in Apex DML operations.
  • You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers, trigger.new is not saved, so a runtime exception is thrown.
  • trigger.old is always read-only.
You cannot delete trigger.new.

How to avoid Recursive trigger:


Example:
     Suppose there is a scenario where in one trigger perform update operation, which results in invocation of second trigger and the update operation in second trigger acts as triggering criteria for trigger one.

Solution:


Class:

public class Utility
{
    public static boolean isFutureUpdate;
}


Trigger:

trigger updateSomething on Account (after insert, after update)
{

    /*  This trigger performs its logic when the call is not from @future */
    if(Utility.isFutureUpdate != true)
    {

        Set<Id> idsToProcess = new Se<Id>();

        for(Account acct : trigger.new)
        {
            if(acct.NumberOfEmployees > 500)
            {
                idsToProcess.add(acct.Id);
            }
        }

        /* Sending Ids to @future method for processing */
        futureMethods.processLargeAccounts(idsToProcess);

    }
}

Class:

public class FutureMethods
{

    @future
    public static void processLargeAccounts(Set<Id> acctIDs)
    {

        List<Account> acctsToUpdate = new List<Account>();

        /* isFutureUpdate is set to true to avoid recursion */
        Utility.isFutureUpdate = true;
    
        update acctsToUpdate;
    }
}

Salesforce Sharing Rule

The terms “Record-Level Access” and “Sharing” are interlinked in Salesforce.com. Sharing enables record-level access control for all custom objects. Sharing can also be enabled for many standard objects such as (such as Account, Contact, Opportunity and Case).
Levels of Record Access
View, Edit, Transfer, Share, and Delete

Default Sharing Access

Default sharing access is set through organization-wide defaults (OWD).

Additional Record-Level Access Types

1. Force.com Managed Sharing
All implicit sharing added by Force.com managed sharing cannot be altered directly using the Salesforce user interface, SOAP, API, or Apex.
Record Ownership
Every record is owned by a user or a queue (in case of custom objects, cases, and leads). The record owner is automatically granted Full Access to the record. This enables them to access the record on all levels (view, edit, transfer, share, and delete).
Role Hierarchy
If “Role Hierarchy” is enabled, users above another users in the hierarchy can have the same level of access to records owned by or shared with users below. This behavior can be disabled for specific custom objects. Role hierarchy is not maintain with sharing records. Role hierarchy access is derived at runtime.
Sharing Rules
With sharing rules, an administrator can automatically grant users within a given group or role access to records owned by specific group of users.
2. User Managed Sharing, also known as “Manual Sharing”
User managed sharing allows the record owner or any user with Full Access to a record to share the record with a user or group of users. This is generally done by an end-user, for a single record. Only the record owner and users above the owner in the role hierarchy are granted Full Access to the record. It is not possible to grant other users Full Access. Users with the “Modify All” object-level permission for the given object or the “Modify All Data” permission can also manually share a record. User managed sharing is removed when the record owner changes or when the access granted in the sharing does not grant additional access beyond the object’s organization-wide sharing default access level.
3. Apex Managed Sharing
 Apex managed sharing provides developers with the ability to support an application’s particular sharing requirements programmatically through Apex or the SOAP API. This type of sharing is similar to Force.com managed sharing. Only users with “Modify All Data
Types of Sharing in Salesforce


Salesforce has the following types of sharing:

1. Force.com Managed Sharing
Force.com managed sharing involves sharing access granted by Force.com based on record ownership, the role hierarchy, and sharing rules:

1.1 Record Ownership
Each record is owned by a user or optionally a queue for custom objects, cases and leads. The record owner is automatically granted Full Access, allowing them to view, edit, transfer, share, and delete the record.

1.2 Role Hierarchy
The role hierarchy enables users above another user in the hierarchy to have the same level of access to records owned by or shared with users below. Consequently, users above a record owner in the role hierarchy are also implicitly granted Full Access to the record, though this behavior can be disabled for specific custom objects. The role hierarchy is not maintained with sharing records. Instead, role hierarchy access is derived at runtime. For more information, see “Controlling Access Using Hierarchies” in the Salesforce online help.

1.3 Sharing Rules
Sharing rules are used by administrators to automatically grant users within a given group or role access to records owned by a specific group of users. Sharing rules cannot be added to a package and cannot be used to support sharing logic for apps installed from Force.com AppExchange. Sharing rules can be based on record ownership or other criteria. You can't use Apex to create criteria-based sharing rules. Also, criteria-based sharing cannot be tested using Apex. All implicit sharing added by Force.com managed sharing cannot be altered directly using the Salesforce user interface, SOAP API, or Apex.

2. User Managed Sharing, also known as Manual Sharing
User managed sharing allows the record owner or any user with Full Access to a record to share the record with a user or group of users. This is generally done by an end-user, for a single record. Only the record owner and users above the owner in the role hierarchy are granted Full Access to the record. It is not possible to grant other users Full Access. Users with the “Modify All” object-level permission for the given object or the “Modify All Data” permission can also manually share a record. User managed sharing is removed when the record owner changes or when the access granted in the sharing does not grant additional access beyond the object's organization-wide sharing default access level.

3. Apex Managed Sharing
Apex managed sharing provides developers with the ability to support an application’s particular sharing requirements programmatically through Apex or the SOAP API. This type of sharing is similar to Force.com managed sharing. Only users with “Modify All Data” permission can add or change Apex managed sharing on a record. Apex managed sharing is maintained across record owner changes.
 Account sharing rules can be based on the record owner or on other criteria, including record type and certain field values. You can define up to 300 account sharing rules, including up to 50 criteria-based sharing rules.
1.      If you plan to include public groups in your sharing rule, confirm that the appropriate groups have been created.
2.      From Setup, click Security Controls | Sharing Settings.
3.      In the Account Sharing Rules related list, click New.
4.      Enter the Label Name and Rule Name. The Label is the sharing rule label as it appears on the user interface. The Rule Name is a unique name used by the API and managed packages.
5.      Select a rule type.
6.      Depending on the rule type you selected, do the following:
      Based on record owner—In the owned by members of line, specify the users whose records will be shared: select a category from the first drop-down list and a set of users from the second drop-down list (or lookup field, if your organization has over 200 queues, groups, roles, or territories).
      Based on criteria—Specify the Field, Operator, and Value criteria that records must match to be included in the sharing rule. The fields available depend on the object selected, and the value is always a literal number or string. Click Add Filter Logic... to change the default AND relationship between each filter.Note
To use a field that’s not supported by criteria-based sharing rules, you can create a workflow rule or Apex trigger to copy the value of the field into a text or numeric field, and use that field as the criterion.
2.      In the Share with line, specify the users who should have access to the data: select a category from the first drop-down list and a set of users from the second drop-down list or lookup field.
3.      Select a setting for Default Account, Contract and Asset Access.
4.      In the remaining fields, select the access settings for the records associated with the shared accounts.
Access Setting
Description
Private
(available for associated contacts, opportunities, and cases only)
Users can’t view or update records, unless access is granted outside of this sharing rule.
Read Only
Users can view, but not update, records.
Read/Write
Users can view and update records.


With sharing rules, you can make automatic exceptions to your organization-wide sharing settings for defined sets of users. For example, use sharing rules to extend sharing access to users in public groups, roles, or territories.Sharing rules can never be stricter than your organization-wide default settings. They simply allow greater access for particular users.
You can create the following types of sharing rules.
Type
Based on
Set Default Sharing Access for
Account owner or other criteria, including account record types or field values
Accounts and their associated contracts, assets, opportunities, cases, and optionally, contacts
Territory assignment
Accounts and their associated cases, contacts, contracts, and opportunities
Campaign owner or other criteria, including campaign record types or field values
Individual campaign records
Case owner or other criteria, including case record types or field values
Individual cases and associated accounts
Contact owner or other criteria, including contact record types or field values
Individual contacts and associated accounts
Custom object owner or other criteria, including custom object record types or field values
Individual custom object records
Lead owner or other criteria, including lead record types or field values
Individual leads
Opportunity owner or other criteria, including opportunity record types or field values
Individual opportunities and their associated accounts
Note
      You can’t include high-volume portal users in sharing rules because they don’t have roles and can’t be in public groups.

      Developers can use Apex to programmatically share custom objects (based on record owners, but not other criteria). This does not apply to User Sharing.