Insert Custom VF into standard layout and refresh both standard layout and Custom VF

<apex:page standardController="Leave_Plan__c" extensions="_Leaveplan_CTE" action="{!approvalNeeded}">
        <center>
            <apex:pageMessages ></apex:pageMessages>                
         
            <apex:outputPanel rendered="{!IF(Leave_Plan__c.Status__c == 'Approved',true,false)}">
                <font color="green" size="2"><b>
                <apex:image id="theImage" value="{!$Resource.Smily}" width="15" height="15"/>Your request has been approved.</b></font>
            </apex:outputPanel><br/><br/>
         
            <apex:outputPanel rendered="{!IF(Leave_Plan__c.Status__c == 'Rejected',true,false)}">
                <font color="red" size="2"><b>
                <apex:image id="theImage1" value="{!$Resource.Sad}" width="15" height="15"/>Your request has been rejected.</b></font>
            </apex:outputPanel>
         
            <apex:outputPanel rendered="{!IF(AND(Leave_Plan__c.Status__c == 'Cancel',CONTAINS($UserRole.Name,'Employee')),true,false)}">
                <font color="red" size="2"><b>
                <apex:image value="{!$Resource.Sad}" width="15" height="15"/>Something went wrong please create new record don't edit this record</b></font>
            </apex:outputPanel>
         
            </center>
            <center><apex:outputLabel rendered="{!showAlert}">
                <apex:image id="theImage2" value="{!$Resource.Smily}" width="15" height="15"/>
                <font color="red" size="2"><b>Please refresh the page.This record has been sent for Approval already.</b></font>
                </apex:outputLabel></center>
                <center><apex:outputLabel rendered="{!showAlert1}">
                <apex:image id="theImage4" value="{!$Resource.Smily}" width="15" height="15"/>
                <font color="red" size="2"><b>You are not an authorized to submit this record for Approval</b></font>
                </apex:outputLabel></center>
            <center>
            <apex:outputpanel rendered="{!refreshPage}" style="margin-left:-30%;">
                <script>
                window.top.location='/{!Leave_Plan__c.id}';
            </script>
            </apex:outputpanel>
            <apex:form >
                <apex:outputPanel rendered="{!requiredSection}">
                <b>Please Select cancel reason : </b>&nbsp; &nbsp;
                <apex:selectList value="{!strComment}" size="1" required="true">
                    <apex:selectOptions value="{!Options}"></apex:selectOptions>
                </apex:selectList><br/>
                <apex:commandButton value="Cancel Leave" action="{!cmdCancelLeave}" title="Cancel Leave" alt="Cancel Leave"/>
              </apex:outputPanel>                              
                    <apex:commandButton value="Approve" action="{!cmdApprove}" rendered="{!approveShow}"/>
                    <apex:commandButton value="Reject" action="{!cmdReject}" rendered="{!rejectShow}" />
                    <apex:commandButton value="Submit for Approval" action="{!cmdSubmitforApproval}"
                    rendered="{!IF(Leave_Plan__c.Status__c=="New Request",true,false)}"/>
                    <apex:commandButton value="Cancel Request" action="{!cmdCancelRequest}"
                    rendered="{!IF(AND(Leave_Plan__c.Status__c!="Cancel",NOT(CONTAINS($UserRole.Name, 'Employee'))),true,false)}"/>
                    <!--<apex:commandButton value="Cancel Leave" action="{!cmdCancelLeave}"                  
                    rendered="{!IF(AND(OR(Leave_Plan__c.Status__c=="New Request",
                                      Leave_Plan__c.Status__c=="Approval Pending",
                                      Leave_Plan__c.Status__c=="Approved",
                                      Leave_Plan__c.Status__c=="Recancelled"),
                                      NOT(CONTAINS($UserRole.name, 'Employee'))),true,false)}"/>-->
                    <apex:commandButton value="Reassign"  action="{!Reassign}" rendered="{!reassignShow}"/>
                    <apex:commandButton value="Cancel" action="{!cmdCancel}" rendered="{!IF(OR(Leave_Plan__c.Status__c=="New Request",
                                      Leave_Plan__c.Status__c=="Approval Pending",
                                      Leave_Plan__c.Status__c=="Approved",
                                      Leave_Plan__c.Status__c=="Recancelled"),true,false)}"/>
                    <apex:commandButton value="Re-Request" action="{!cmdRerequest}"
                    rendered="{!IF(Leave_Plan__c.Status__c=="Rejected",true,false)}"/>
            </apex:form>
        </center>
</apex:page>


Apex:--

public class _Leaveplan_CTE{
    //@Initial varialbles declaration
    public final Leave_Plan__c leaveIds ;
    public final Leave_Plan__c leaveDetail;
    public boolean refreshPage {get;set;}
    public boolean approveShow {get;set;}
    public boolean rejectShow {get;set;}
    public boolean reassignShow {get;set;}
    public boolean showAlert {get;set;}
    public boolean showAlert1 {get;set;}
    public boolean cmdCancelLeaveShow  {get;set;}
    public boolean cmdCancelShow {get;set;}
    public boolean requiredSection {get;set;}
    public string strComment {get;set;}
    //@Standard controller defination
    public _Leaveplan_CTE(Apexpages.standardcontroller controller){
        refreshPage = false;
        showAlert = false;
        showAlert1 = false;
        cmdCancelLeaveShow = true;
        requiredSection = false;
        this.leaveIds = (Leave_Plan__c) controller.getRecord();
        //@fetching complete record details from standard UI to class based on Id
        leaveDetail = [select id,name,Company__c,Current_Approval_Status__c,Date_From__c,Date_To__c,
                      Email_Id__c,Employee_ID__c,Employee_Name1__c,First_Approval__c,Description__c,
                      Leave_Type__c,Location__c,Manager_Approval__c,Number_of_Days__c,Request_Submitted_on__c,
                      Status__c,Time_out_of_office__c,Employee_Name__c from Leave_Plan__c where id =:leaveIds.id limit 1];
    }
    //@This method will call at the time of user clicks on submit for approval process button
    public pageReference cmdSubmitforApproval(){
        cmdCancelLeaveShow = true;
        User usr = [select id,name,userroleid,UserRole.Name from user where userroleid=:UserInfo.getUserRoleId() limit 1];
        Leave_Plan__c l = new Leave_Plan__c();
        l = [select id,status__c from Leave_Plan__c where id=:leaveDetail.id];
        if(l.status__c == 'Approval Pending'){
           // ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Info, 'Your Lead is sent to Approval process already.');
            //ApexPages.addMessage(msg);
            showAlert = true;
            return null;
        }
        if(usr.UserRole.Name.contains('Employee')){
        try{
         Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
           req1.setObjectId(leaveIds.id);
           Approval.ProcessResult result = Approval.process(req1);
           refreshPage = true;
           }catch(Exception e){
               ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error occured' + e.getMessage()));
           }
        return null;
        }else{
            showAlert1 = true;
            return null;
        }
    return null;
    }
    //@Method: This will call and display Approve or Reject buttons based on user group membership
    public void approvalNeeded(){
        cmdCancelLeaveShow = true;
        map<Id,Group> mapIdGroup = new map<Id,Group>([SELECT Id from Group where RelatedId = : UserInfo.getUserRoleId()]);
                    LIST < GroupMember > actList = [SELECT GroupId from GroupMember where UserOrGroupId =: UserInfo.getUserId() OR
                                             UserOrGroupId IN : mapIdGroup.keySet()];
                    set<Id> actId = new set<Id>();
                    if (actList.size() > 0) {
                        for(GroupMember g:actList){
                            actId.add(g.GroupId);
                        }
                    }

                    Integer i = [SELECT count()
                        FROM ProcessInstanceWorkItem
                        WHERE ProcessInstance.Status = 'Pending'
                        AND ProcessInstance.TargetObjectId = : leaveIds.Id AND(ActorId IN : actId OR ActorId = : UserInfo.getUserId())
                        LIMIT 1
                    ];

                    if (i > 0) {
                        approveShow = true;
                        rejectShow = true;
                        reassignShow = true;
                    } else {
                        approveShow = false;
                        rejectShow = false;
                        reassignShow = false;
                    }
    }
    //@Method:This method will call at the time of user clicks on Approval button
    public pageReference cmdApprove(){
        cmdCancelLeaveShow = true;
        Set<id> actId = new Set<Id>();
        //@Fetching group membership here
        map<Id,Group> mapIdGroup = new map<Id,Group>([SELECT Id from Group where RelatedId = : UserInfo.getUserRoleId()]);
        List<GroupMember > grp = [SELECT GroupId from GroupMember where UserOrGroupId =: UserInfo.getUserId() OR
                                  UserOrGroupId IN : mapIdGroup.keySet()];
        for(GroupMember g : grp){
            actId.add(g.GroupId);
        }
        List <ProcessInstanceWorkItem> items = [select id,processinstanceid,processinstance.status,processinstance.targetobjectid,ActorId from ProcessInstanceWorkitem
            where processinstance.status='Pending' and
            processinstance.targetobjectid = :leaveIds.id AND(ActorId = :UserInfo.getUserId() or ActorId=:actId ) limit 1];
            Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
            req.setAction('Approve');
            req.setComments('Approved Happy vacation');
            req.setWorkitemId(items[0].Id);
            Approval.ProcessResult result = Approval.process(req);
            refreshPage = true;
    return null;  
    }
    //@Method : This method will call at the time of Lead or Manager clicks on reject button
    public pageReference cmdReject(){
        try{
        cmdCancelLeaveShow = true;
        Set<id> actId = new Set<Id>();
        map<Id,Group> mapIdGroup = new map<Id,Group>([SELECT Id from Group where RelatedId = : UserInfo.getUserRoleId()]);
        List<GroupMember > grp = [SELECT GroupId from GroupMember where UserOrGroupId =: UserInfo.getUserId() OR
                                  UserOrGroupId IN : mapIdGroup.keySet()];
        for(GroupMember g : grp){
            actId.add(g.GroupId);
        }
        List <ProcessInstanceWorkItem> items = [select id,processinstanceid,processinstance.status,processinstance.targetobjectid,ActorId from ProcessInstanceWorkitem
            where processinstance.status='Pending' and
            processinstance.targetobjectid = :leaveIds.id AND(ActorId = :UserInfo.getUserId() or ActorId=:actId ) limit 1];
            Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
            req.setAction('Reject');
            req.setComments('Rejected adjust your days');
            req.setWorkitemId(items[0].Id);
            Approval.ProcessResult result = Approval.process(req);
            refreshPage = true;
            }catch(Exception e){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error occured' + e.getMessage()));
            }
    return null;  
    }
    //@Method:This method will refresh standard and custom UI
    public pageReference cmdCancel(){
        refreshPage = true;
    return null;
    }
    //@Method : Re-request will happen here
    public pageReference cmdRerequest(){  
     try{
     User usr = [select id,name,userroleid,UserRole.Name from user where userroleid=:UserInfo.getUserRoleId() limit 1];
     if(usr.UserRole.Name.contains('Employee')){}
     cmdCancelLeaveShow = true;
     Leave_Plan__c l1 = new Leave_Plan__c();
        l1 = [select id,status__c,Date_From__c,Date_To__c,First_Approval__c,Manager_Approval__c,
            Current_Approval_Status__c from Leave_Plan__c where id=:leaveDetail.id limit 1];
            l1.status__c = 'New Request';
            l1.Date_From__c = null;
            l1.Date_To__c = null;
            l1.Time_out_of_office__c = null;
            l1.First_Approval__c = false;
            l1.Manager_Approval__c = false;
            l1.Current_Approval_Status__c = '';
            Database.update(l1);
            refreshPage = true;
       }catch(Exception e){
           ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error occured' + e.getMessage()));
           refreshPage = true;
       }      
     refreshPage = true;
     return null;
    }
    //@Method:method re-assignment will be done here
   public PageReference Reassign(){
       try{
        cmdCancelLeaveShow = true;
        List<ProcessInstanceWorkItem> workItemList = [Select p.ProcessInstance.Status, p.ProcessInstance.TargetObjectId,p.ProcessInstanceId,p.OriginalActorId,p.Id,p.ActorId
        From ProcessInstanceWorkitem p where p.ProcessInstance.TargetObjectId = :leaveIds.Id];
        Leave_Plan__c l = new Leave_Plan__c();
        l = [select id from Leave_Plan__c where id=:leaveDetail.id limit 1];
        String retId =l.id;
        String strAppId = workItemList[0].Id;
        String partialURL = '/' + strAppId + '/e?et=REASSIGN&retURL=%2F'+retId;
        PageReference pageRef = new PageReference(partialURL);
        refreshPage = true;
        return pageRef;
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,''+ e.getMessage()));
        }
        return null;
        }
    //@Method:It will cancel leaves and leave process will end here
    /*public Pagereference cmdCancelLeave(){
        try{
     
       Set<id> actId = new Set<Id>();
        map<Id,Group> mapIdGroup = new map<Id,Group>([SELECT Id from Group where RelatedId = : UserInfo.getUserRoleId()]);
        List<GroupMember > grp = [SELECT GroupId from GroupMember where UserOrGroupId =: UserInfo.getUserId() OR
                                  UserOrGroupId IN : mapIdGroup.keySet()];
        for(GroupMember g : grp){
            actId.add(g.GroupId);
        }
        if(leaveDetail.status__c == 'Approval Pending'){
        List <ProcessInstanceWorkItem> items = [select id,processinstanceid,processinstance.status,processinstance.targetobjectid,ActorId from ProcessInstanceWorkitem
            where processinstance.status='Pending' and
            processinstance.targetobjectid = :leaveIds.id AND(ActorId = :UserInfo.getUserId() or ActorId=:actId ) limit 1];
            Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
            req.setAction('Reject');
            req.setComments('Cancelled apply for new leave');
            req.setWorkitemId(items[0].Id);
            Approval.ProcessResult result = Approval.process(req);
            }
            Leave_Plan__c l = new Leave_Plan__c();
            l = [select id,status__c,recordtypeid from Leave_Plan__c where id=:leaveDetail.id limit 1];
            l.status__c = 'Cancel';
            l.First_Approval__c = false;
            l.Manager_Approval__c = false;
            l.recordtypeid = '012280000005BKGAA2';
            Database.update(l);
            refreshPage = true;
            reassignShow = false;
            approveShow = false;
            rejectShow = false;
            cmdCancelLeaveShow = false;
            cmdCancelShow = false;
            }catch(Exception e){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,''+ e.getMessage()));
            }
    return null;  
    }*/
    //@Method:It will cancel leaves and leave process will end here
    public Pagereference cmdCancelLeave(){
        ObjectRecordTypeIds__c orgConstant = ObjectRecordTypeIds__c.getInstance();
        String closedLeaveRecordtypeId = orgConstant.Marketing_Lead_RecordType__c;
        try{
        if(leaveDetail.status__c == 'Approval Pending'){
        List <ProcessInstanceWorkItem> items = [select id,processinstanceid,processinstance.status,processinstance.targetobjectid,ActorId from ProcessInstanceWorkitem
            where processinstance.status='Pending' and processinstance.targetobjectid = :leaveIds.id limit 1];
            Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
            req.setAction('Reject');
            req.setComments(strComment);
            req.setWorkitemId(items[0].Id);
            Approval.ProcessResult result = Approval.process(req);
            }
            Leave_Plan__c l = new Leave_Plan__c();
            l = [select id,status__c,First_Approval__c,Manager_Approval__c,recordtypeid,Cancel_Reason__c from Leave_Plan__c where id=:leaveDetail.id limit 1];
            l.status__c = 'Cancel';
            l.First_Approval__c = false;
            l.Manager_Approval__c = false;
            l.Cancel_Reason__c=strComment;
            l.recordtypeid = ObjectRecordTypeId__c.getInstance('Closed Leave').Marketing_Lead_RecordType__c;
            Database.update(l);
            refreshPage = true;
            reassignShow = false;
            approveShow = false;
            rejectShow = false;
            cmdCancelLeaveShow = false;
            cmdCancelShow = false;
            }catch(Exception e){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,''+ e.getMessage()));
            }
    return null;  
    }
    public pagereference cmdCancelRequest(){
    requiredSection = true;
    reassignShow = false;
    approveShow = false;
    rejectShow = false;
 
    return null;
    }
    public List<SelectOption> getOptions(){
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('Adjust your days','Adjust your days'));
        options.add(new SelectOption('Cancelled no requalification','Cancelled no requalification'));
        options.add(new SelectOption('Cancel your request','Cancel your request'));
        options.add(new SelectOption('Something went wrong on dates','Something went wrong on dates'));
        options.add(new SelectOption('Dont plan this week','Dont plan this week'));
        return options;
    }
    //@Method : Invoke apex method at the time of user clicking send to leaves button
    public pagereference cmdSendLeave(){
        User usr = [select id,name,userroleid,UserRole.Name from user where userroleid=:UserInfo.getUserRoleId() limit 1];
     if(usr.UserRole.Name.contains('Employee')){}
     cmdCancelLeaveShow = true;
       
     Leave_Plan__c l1 = new Leave_Plan__c();
        l1 = [select id,status__c,Date_From__c,Date_To__c,First_Approval__c,Manager_Approval__c,
            Current_Approval_Status__c from Leave_Plan__c where id=:leaveDetail.id limit 1];
            //Map<string,ObjectRecordTypeId__c> orga =ObjectRecordTypeId__c.getAll();
            //if(orga.containsKey('Closed Leave')){
            //l1.recordtypeId = orga.get(l1.id).name;
            //}
            l1.status__c = 'send to report';
            l1.Date_To__c = null;
            l1.Time_out_of_office__c = null;
            l1.First_Approval__c = false;
            l1.Manager_Approval__c = false;
            l1.Current_Approval_Status__c = '';
            Database.update(l1);          
            refreshPage = true;
            requiredSection = true;
            reassignShow = false;
            approveShow = false;
            rejectShow = false;
     return null;  
    }
    public static void deletePreventTriggerMethod(List<Leave_Plan__c> leaveIds){
        User currentUserRole = [select id,profileid,profile.name from User where id=:UserInfo.getUserId() limit 1 ];
        if(!currentUserRole.profile.name.contains('System Administrator')){
        for(Leave_Plan__c leaveId : leaveIds){
            leaveId.addError('You are not an authorized to delete this record contact your Admin');
        }
     }
   }
}

Choosen Picklist and jQuery form validation in visualforce with css



VF Code:

<apex:page controller="myController" docType="html-5.0" standardStylesheets="false" sidebar="false" showHeader="false">  
        <apex:pageMessages ></apex:pageMessages>
        <apex:includeScript value="{!$Resource.jQuery_Min}"/>      
        <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />  
        <apex:includeScript value="https://ajax.microsoft.com/ajax/jquery.validate/1.6/jquery.validate.min.js"/>      
        <apex:includeScript value="{!$Resource.chosen_jquery_min}"/>
        <apex:stylesheet value="{!$Resource.cssFile}"/>
        <apex:stylesheet value="{!$Resource.chosen_min}"/>
        <style>
            .choiceChosen, .productChosen {
                  width: 300px ;
             }
            .error{
              color:red;
            }
        </style>
        <script>
            $(document).ready(function(){
             
                $(".choiceChosen, .productChosen").chosen({});
                  $(".choiceChosen").change(function(){
                    if($(".choiceChosen option:selected").val()=="no"){
                      $(".productChosen option[value='2']").attr('disabled',true).trigger("chosen:updated");
                      $(".productChosen option[value='1']").removeAttr('disabled',true).trigger("chosen:updated");
                    } else {
                      $(".productChosen option[value='1']").attr('disabled',true).trigger("chosen:updated");
                      $(".productChosen option[value='2']").removeAttr('disabled',true).trigger("chosen:updated");
                    }
                })
             
            });
        </script>
        <apex:form id="CustomerForm">
        <body>
            <br/><br/><br/><br/>
            <div id="wrapper">
                <fieldset style="width: 600px;!important">
                    <legend>Wait List form for Attendee </legend>
                    <div>
                        <label id=""></label>
                        <apex:inputText value="{!FirstName}" html-placeholder="First Name" id="firstName"/>
                    </div>
                    <div>
                        <apex:inputText value="{!LastName}" html-placeholder="Last Name" id="lastName"/>
                    </div>
                    <div>
                        <apex:inputSecret value="{!password}" html-placeholder="Password" id="password"/>
                    </div>
                    <div>
                        <apex:inputText value="{!email}" html-placeholder="Email" id="emailID"/>
                    </div>
                      <div>
                          <apex:selectList styleClass="choiceChosen" value="{!InactiveListValue}" id="InactiveList">
                              <apex:selectOptions value="{!InactiveList}"/>
                          </apex:selectList>
                      </div><br/>
                      <div>
                          <apex:selectList styleClass="choiceChosen" multiselect="true" value="{!countryListValue}" id="countryList">
                              <apex:selectOptions value="{!countryList}"/>
                          </apex:selectList>
                      </div>
                      <apex:commandButton action="{!createRecord}" value="Submit" id="submit" styleClass="submit"/>
                </fieldset>
            </div>
        <script type="text/javascript">
            $('[id$=CustomerForm]').validate();
            $('[id$=firstName]').rules("add",{
                required: true,
                minlength: 5,
                maxlength: 50,            
                messages:{
                required:"Required First Name",
                minlength: jQuery.validator.format("Please etner at least 5 characters are necessary"),
                }                        
            });
            $('[id$=lastName]').rules("add",{
                required: true,
                minlength: 5,
                maxlength: 50,            
                messages:{
                required:"Required Last Name",
                minlength: jQuery.validator.format("Please etner at least 5 characters are necessary"),
                }                        
            });
            $('[id$=emailID]').rules("add",{
                required: true,
                email:true,            
                messages:{
                required:"Required Email",
                email: jQuery.validator.format("Please enter valid email id"),
                }                        
            });
            $('[id$=password]').rules("add",{
                required: true,                        
                messages:{
                required:"Required Password",              
                }                        
            });
                   
        </script>
        </body>
    </apex:form>

</apex:page>

Apex Class :--

public with sharing class myController {
    public String email { get; set; }
    public String password { get; set; }
    public String LastName { get; set; }
    public String FirstName { get; set; }
    public string countryListValue { get;set; }
    public string InactiveListValue {get;set;}
    public static Map<string,MappingDetails__c> custMap;
    static {
       custMap = MappingDetails__c.getAll();      
    }
    public List<SelectOption> getCountryList(){
        List<SelectOption> options =  new List<SelectOption>();
        for(String custDetails : custMap.keySet()){
            options.add(new selectoption(custDetails,custDetails));
        }
    return options;
    }
     public List<SelectOption> getInactiveList(){
        List<SelectOption> options =  new List<SelectOption>();
        for(MappingDetails__c custDetails : custMap.values()){
            options.add(new selectoption(custDetails.Inactive_Queue__c,custDetails.Inactive_Queue__c));
        }
    return options;
    }
    public string testMessage {get;set;}
    public PageReference createRecord() {
        testMessage = FirstName +'-'+LastName+'-'+email+'-'+password+'-'+countryListValue;
        Car_Models__c c = new Car_Models__c();
        c.recordtypeid=Schema.SObjectType.Car_Models__c.getRecordTypeInfosByName().get('Employee Details').getRecordTypeId();
        c.First_Name__c = FirstName ;
        c.Last_Name__c = LastName;
        c.Password__c = password;
        c.Email__c = email;
        c.Inactive_Queue_Name__c = InactiveListValue ;
        c.Country_List__c = countryListValue;
        insert c;
        return new pagereference('/'+c.id);
    }
}

Salesforce Custom button with Javascript & jQuery model dialogue window for sending email to customers

jQuery Code Snippet :

{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js')}
{!REQUIRESCRIPT('//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js')}
{!REQUIRESCRIPT('/soap/ajax/15.0/connection.js')}
{!REQUIRESCRIPT('/soap/ajax/15.0/apex.js')}
var emailFinalText;
var descriptionFinalText;
try{
  jQuery(function(){
    /*Append the jQuery CSS CDN Link to the Head tag.*/
    jQuery('head').append('<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/start/jquery-ui.css" type="text/css" />');  
    /*Create the HTML(DIV Tag) for the Dialog.*/
    var html = '<form id="dialog" title="Send Email">'
+'<table style="width:100%">'
+'<tr><th>Email</th></tr><tr><td><input style="width: -webkit-fill-available !important;" id="email" type="email" name="email"></td></tr>'
+'<tr><th>Message</th></tr><tr><td><textarea style="width: -webkit-fill-available;" id="messageDescription" name="comment" rows="13" cols="45"></textarea></td></tr>'
+'</table>'
+'</form>';  
    /*Check if the Dialog(DIV Tag) already exists if not then Append the same to the Body tag.*/
    if(!jQuery('[id=dialog]').size()){
      jQuery('body').append(html);
    }
    /*Open the jQuery Dialog.*/
    jQuery( "#dialog" ).dialog({
   bgiframe: true,
autoOpen: true,
resizable: false,
maxWidth:500,
maxHeight:400,
width: 500,
height: 400,
modal: true,
      show:{
        duration: 1000
      },
      hide:{
        duration: 1000
      },
      /*Adding value to display*/
      open: function( event, ui ){
      var emailId = "{!Lead.Email}";
      var leadDesc ="{!Lead.FirstName}";
      emailFinalText = document.getElementById("email").value = emailId;
      descriptionFinalText = document.getElementById("messageDescription").value = "Hello "+leadDesc+"\n\nPlease confirm if you are interested in buying the product ?\n\nRegards,\n{!$User.FirstName}";
      },
      buttons:{
        "Send": function(){        
           /*alert("call Apex method.");*/
                var contextUser = sforce.apex.execute("sendEmailToUser_Cls", "sendEmail", {emailFinalTextApex:$('#email').val(),descriptionFinalTextApex:$('#messageDescription').val()});
                alert(contextUser);
                jQuery( this ).dialog( "close" );
        },
        Cancel: function(){
          jQuery( this ).dialog( "close" );
        }
      }
    });
  });
}catch(e){
    alert('An Error has Occured. Error: ' + e);
}

Apex Soap code snippet:

global class sendEmailToUser_Cls{
   webService static String sendEmail(String emailFinalTextApex,string descriptionFinalTextApex) {
       List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();
       if(String.isNotBlank(emailFinalTextApex) && String.isNotBlank(descriptionFinalTextApex)){
           Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
           List<String> sendTo = new List<String>();
           sendTo.add(emailFinalTextApex);
           mail.setToAddresses(sendTo);
           mail.setSenderDisplayName('Official Bank of Nigeria');
           mail.setReplyTo('fgangana@cisco.com');
           mail.setHtmlBody(descriptionFinalTextApex);
           mails.add(mail);
           Messaging.sendEmail(mails);
           return 'Success: Mail has been sent';
       }else{
           return 'Error:Please fillout Email and Description fields';
       }
   }
}

Sample Screenshot:




Matching rules with apex salesforce

De-Dupe - 
                 Before going to implement dedupe logic using batch apex or regular apex, make sure we need to create matching rules with certain criteria and duplicate rules for same.

Example Here you go -

               Now implemet the actual logic from trigger or apex class based on your requirement. I am going to test the same stuf using developer console on lead object.

Apex Code & Trigger Snippet -

trigger Dedupe_Trg on Lead (after insert) {
   
    public static List<lead> leadIds = new List<lead>();
    public static String query;  
    if(Trigger.isAfter && Trigger.isInsert){
        for(Lead l : trigger.newMap.Values()){
            if(l.status=='Pre-Prospect' && l.dedupe__c=='dedupe'){
                leadIds.add(l);
        }
    }          
    if(!leadIds.isEmpty()){
       String ids = getLeadIdsString(leadIds);
       if(String.isNotBlank(ids)){
           query = 'select id';
           for(Schema.FieldSetMember fld :SObjectType.Lead.FieldSets.DedupeFiedSet.getFields()) {
                query+= ', ' + fld.getFieldPath();
            }
            query+= ' from lead WHERE ID in ('+ ids +')';
       }
    }  
    if(String.isNotBlank(query)){
        Database.executeBatch(new Lead_Deduper(query));
    }
   }
   public static String getLeadIdsString(List<Lead> input){
        String result = '';      
        for (Lead l: input){          
            result = result + '\'' + l.Id + '\',';
            system.debug('result first------'+result);
        }
        result = result.substring(0, result.length()-1);
        system.debug('result Second------'+result);
        return result;
    }    
}
----------------------------------------

global class Lead_Deduper implements Database.Batchable < sObject > {
    //@Class level variable declaration here
    global String query;
    global List<sObject> tempMatchRecordId;
   
    //@Method: Constructor for getting query string from trigger
    global Lead_Deduper(String query){
        this.query = query;
    }
    //@Method: Start method for fetching records from query
    global Database.QueryLocator start(Database.BatchableContext info) {
        return Database.getQueryLocator(query);
    }
    //@Method: Execute will do actual operations
    global void execute(Database.BatchableContext info, List <Lead> scope) {
        for(Lead l : scope){
            If(l.status=='Pre-Prospect'){
                l.status='New Prospect';
                l.Dedupe__c= Null;
                l.Dedupe_Processing__c = True;
            }
        }
       
        scopeIdentifier(scope);
    }
    //@Method: This is responsible for gettting both existing and latest lead ids
    global static Lead getLatestExistingLead(Datacloud.MatchRecord[] matchRecords){
        Lead existingLeadId;
        for (Datacloud.MatchRecord matchRecord : matchRecords) {
            existingLeadId = (Lead)matchRecord.getRecord();
        }
        system.debug('exsting lead id ----->>>'+existingLeadId);
        return existingLeadId;
    }
    //@Method: Finish logic for sending emails
    global void finish(Database.BatchableContext info){
        system.debug('Finally i am success...');
    }
    //@Method: This method will identify the duplicate records based on new record using datacloud namespace classes and matching rules defined in the system
    global static void scopeIdentifier(List<Lead> scope){
        // Optionally, set DML options here, use “DML” instead of “false”
        //   in the insert()
        // Database.DMLOptions dml = new Database.DMLOptions();
        // dml.DuplicateRuleHeader.allowSave = true;
        // dml.DuplicateRuleHeader.runAsCurrentUser = true;
        Database.SaveResult[] saveResult  = Database.Update(scope,false);
        Map <Id,Id> duplicateLeadIds = new Map <ID,ID> ();
        Integer i=0;
        for (Database.SaveResult sr: saveResult){
        if (sr.isSuccess()){
            scope.remove(i);
        }else{
            for (Database.Error error: sr.getErrors()){
                // If there are duplicates, an error occurs
                // Process only duplicates and not other errors
                // (e.g., validation errors)
                if (error instanceof Database.DuplicateError){
                    // Handle the duplicate error by first casting it as a
                    // DuplicateError class
                    // This lets you use methods of that class
                    // (e.g., getDuplicateResult())
                    Database.DuplicateError duplicateError = (Database.DuplicateError) error;
                    Datacloud.DuplicateResult duplicateResult = duplicateError.getDuplicateResult();
                    // Return only match results of matching rules that
                    // find duplicate records
                    Datacloud.MatchResult[] matchResults = duplicateResult.getMatchResults();
                    // Just grab first match result (which contains the
                    // duplicate record found and other match info)
                    Datacloud.MatchResult matchResult = matchResults[0];
                    Datacloud.MatchRecord[] matchRecords = matchResult.getMatchRecords();
                    Lead existingLead = getLatestExistingLead(matchRecords);
                    duplicateLeadIds.put(scope.get(i).Id,existingLead.Id);
                }else {
                }
            }
            i++;
            }
        }
        List<Suppressed_Lead__c > suppressList = new List<Suppressed_Lead__c>();
        // Add matched record to the duplicate records variable
        for(Lead led : scope){
            led.status = 'Inactive';
            led.Dedupe_Processing__c = false;
            led.Active_Lead_Id_Reason__c = 'https://mysalesproductforce-dev-ed.my.salesforce.com/'+duplicateLeadIds.get(led.id);
            led.Supperession_Reason__c = 'Duplicate lead has been found with same email or customer name';
            Suppressed_Lead__c sup = new Suppressed_Lead__c(Active_Lead__c=led.id,Suppressed_Lead__c=duplicateLeadIds.get(led.id),Description__c=led.description);          
            suppressList.add(sup);
        }
        Database.update(scope,false);
        Map<string,string> queueDetailsUpdate = getQueueDetails(scope);
        for(lead l : scope){
            l.ownerId = queueDetailsUpdate.get(l.country__c);
        }
        Database.update(scope,false);
        if(!suppressList.isEmpty()){
            Database.insert(suppressList,false);
        }
        //List<Lead> leads = [select id,firstname,leadsource,Active_Lead_Id_Reason__c,annualrevenue ,Supperession_Reason__c,lastname,email,description,company,Dedupe__c,Dedupe_Processing__c,status from lead WHERE ID IN : scope];
        String queryString = 'select id';
        //Getting fields from fieldset from lead object
        for(Schema.FieldSetMember fld :SObjectType.Lead.FieldSets.DedupeFiedSet.getFields()) {
            queryString+= ', ' + fld.getFieldPath();
        }
        queryString+= ' from lead WHERE  ID IN : scope ';
       
        //@Response : Creating new response record based on lead information        
        List<Response__c> resp = createResponse(Database.query(queryString));
        system.debug(resp);
        if(resp!=Null && !resp.isEmpty()){
            insert resp;
            system.debug(resp[0].id);
        }      
    }
    //@Method: Create one dummy response using lead details and tagged under the same lead id
    global static List<Response__c> createResponse(List<Lead> scope){
        List<Response__c> response = new List<Response__c>();
        for(Lead l : scope){
            Response__c r = new Response__c();
                r.name = system.now()+'-'+l.firstname+' '+l.lastname;
                r.Is_Suppressed__c = true;
                r.Lead__c = l.id;
                r.Revenue__c = l.annualrevenue;
                r.Description__c = l.Description;
                r.Source__c = l.leadsource;
            response.add(r);
            system.debug(response);
        }
        return response;
    }
    //@Method: This method is reposible for getting Queue name based on country name from lead record
    global static Map<String,string> getQueueDetails(List<Lead> scope){
        Set<String> queueName = new Set<String>();
        Map<String,string> queueMap = new Map<String,string>();
        for(Lead sc : scope){
            if(sc.country__c != Null){
                queueName.add(sc.Country__c);
            }          
        }
        for(QueueSobject q : [Select Id, QueueId, Queue.Name, SobjectType from QueueSobject where queue.name=:queueName]){
            queueMap.put(q.queue.name,q.queueid);
        }
        return queueMap;
    }  
}

Featured

What is Cryptography in salesforce and what are all the algorithms provided by them ?

A). It is a security protocal between two systems. Lets say we are integration two systems without any encrytion mechanism then hackers wil...

Popular