• SalesforceAddict
  • NEWBIE
  • 75 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 14
    Replies
Apex Class===


public class LoginController {
    public static String FinalString;
    public static String userEmail;
    Public String UserName{get;set;}
    Public String Password{get;set;}
    Public Boolean IsLoggedIn{get;set;}
    Public String PortalOwnerId{get;set;}
    Public String LogInPlace{get;set;}
    Public Boolean UserNamePasswordMatched{get;set;}
    public String AccountRecordTypeId{get;set;}
    public Account acc{get;set;}
    public String accId{get;set;}
    public Account acc1{get;set;}
    public Account accConfirmPassword{get;set;}
    public Account accIdToChangePassword{get;set;}
    public list<account> accList{get;set;}
    public static list<String> setToAddresses{get;set;}
    public String PortalUserType{get;set;}
    public Boolean isBlankPassword{get;set;}
    public String accIdToGetCurrentPage{get;set;}
     public Boolean isActive{get;set;}
    
    
    public LoginController(){
        acc=new Account();
        acc1=new Account();
        accConfirmPassword=new Account();
        accList = new list<account>();
        isLoggedIn=true;
        isBlankPassword = true;
        UserName='';
        AccountRecordTypeId=Schema.SObjectType.Account.getRecordTypeInfosByName().get('Professional').getRecordTypeId();
        if(userinfo.getUserId()==System.Label.SiteUserId){
            LogInPlace='Site';
        }else{
            LogInPlace='Salesforce';
        }
        
        if(ApexPages.currentPage().getCookies().get('Username') != null && ApexPages.currentPage().getCookies().get('PassWord') != null && ApexPages.currentPage().getCookies().get('Type') != null){
            String CookieUserName=ApexPages.currentPage().getCookies().get('Username').getValue();
            String CookiePassWord=ApexPages.currentPage().getCookies().get('PassWord').getValue();
            Boolean IsVerifiedUser=false;
            for(Account acc:[SELECT Id,Name,User_Name__c,Password__c,Portal_User_Type__c FROM Account WHERE User_Name__c=: CookieUserName AND Password__c=: CookiePassWord AND RecordTypeId=:AccountRecordTypeId]){
                PortalOwnerId=acc.id;
                IsVerifiedUser=true;
                isLoggedIn=true;
                PortalUserType=acc.Portal_User_Type__c ;
                if(String.IsNotBlank(PortalUserType)){
                    if(PortalUserType.contains('Pioneer') && !PortalUserType.contains('PathFinder')){
                        Cookie portaltypeStore = new Cookie('Type','Pioneer',null,900,true);
                        ApexPages.currentPage().setCookies(new Cookie[]{portaltypeStore});
                    }
                    else{
                        Cookie portaltypeStore = new Cookie('Type','PathFinder',null,900,true);
                        ApexPages.currentPage().setCookies(new Cookie[]{portaltypeStore});
                    }
                }
                Cookie UserStore = new Cookie('Username',acc.User_Name__c,null,900,true);
                Cookie passwordStore = new Cookie('PassWord',acc.Password__c,null,900,true);
                ApexPages.currentPage().setCookies(new Cookie[]{UserStore});
                ApexPages.currentPage().setCookies(new Cookie[]{passwordStore});   
            }
            if(!IsVerifiedUser){
                isLoggedIn=false;
            }
        }else{
            isLoggedIn=false;
        }
        
    }
    
    public Pagereference SubmitPage(){
        if(String.IsNotBlank(UserName) && String.IsNotBlank(PassWord)){
            UserNamePasswordMatched=false;
            for(Account acc:[SELECT Id,User_Name__c,Password__c,Portal_User_Type__c,isActivate__c FROM Account WHERE User_Name__c=: UserName AND Password__c=: PassWord AND RecordTypeId=:AccountRecordTypeId]){
                if(acc.Portal_User_Type__c != null && acc.Password__c !=null){
                    PortalOwnerId=acc.id;
                    UserNamePasswordMatched = true;
                    isActive = true;
                    Cookie UserStore = new Cookie('Username',UserName,null,900,true);
                    Cookie passwordStore = new Cookie('PassWord',PassWord,null,900,true);
                    ApexPages.currentPage().setCookies(new Cookie[]{UserStore});
                    ApexPages.currentPage().setCookies(new Cookie[]{passwordStore});
                    PortalUserType=acc.Portal_User_Type__c ;
                    if(String.IsNotBlank(PortalUserType)){
                        if(PortalUserType.contains('Pioneer') && !PortalUserType.contains('PathFinder')){
                            Cookie portaltypeStore = new Cookie('Type','Pioneer',null,900,true);
                            ApexPages.currentPage().setCookies(new Cookie[]{portaltypeStore});
                        }
                        else{
                            Cookie portaltypeStore = new Cookie('Type','PathFinder',null,900,true);
                            ApexPages.currentPage().setCookies(new Cookie[]{portaltypeStore});
                        }
                    }
                    
                    if(acc.isActivate__c){
                        //isActive = true;
                        
                        if(LogInPlace=='Site'){
                            PageReference pg = new PageReference('/Portal/PathFinderLinksVf');
                            if(String.isNotBlank(ApexPages.CurrentPage().getParameters().get('retUrl')))
                                pg = new PageReference(ApexPages.CurrentPage().getParameters().get('retUrl'));
                                pg.setRedirect(false);
                                return pg; 
                        }else{
                            PageReference pg = new PageReference('/apex/PathFinderLinksVf');
                            if(String.isNotBlank(ApexPages.CurrentPage().getParameters().get('retUrl')))
                                pg = new PageReference(ApexPages.CurrentPage().getParameters().get('retUrl'));
                                pg.setRedirect(false);
                                return pg; 
                        }
                        
                    
                    }else{
                        return null;
                    
                    }
                        
                    
                    
                }
                
                
            }
        }
        return null;
    }
    
    public PageReference VerifyPassword() {
        System.debug('isLoggedIn:- '+isLoggedIn);
        if(isLoggedIn){
            if(LogInPlace=='Site'){
                PageReference pg = new PageReference('/Portal/PathFinderLinksVf');
                pg.setRedirect(false);
                return pg; 
            }else{
                PageReference pg = new PageReference('/apex/PathFinderLinksVf');
                pg.setRedirect(false);
                return pg; 
            }
            
        }
        return null;
    }
public with sharing class ContactEditController {
    Public Contact con{get;set;}
    Public Boolean DuplicateEmailFound{get;set;}
    Public String ButtonClicked{get;set;}
    Public ApexPages.StandardController stdController{get;set;}
    public ContactEditController(ApexPages.StandardController controller) {
        stdController=controller;
        con=(Contact)controller.getRecord();
        con.ownerId=userinfo.getUserId();
        DuplicateEmailFound=false;
    }
    
    Public pagereference Cancel(){
        Pagereference pref=stdController.Cancel();
        return pref;
    }
    
    Public Void CheckDuplicateEmail(){
        String searchTerms = '';
        if(String.IsNotBlank(con.Email)){
            searchTerms+= '("' + con.Email + '")';
        }
        
        if(String.IsNotBlank(con.E_Mail2__c)){
            if(!String.isEmpty(searchTerms)){
                searchTerms += ' OR ';
            }

            searchTerms+= '("' + con.E_Mail2__c+ '")';
        }
        
        if(String.IsNotBlank(con.E_Mail3__c)){
            if(!String.isEmpty(searchTerms)){
                searchTerms += ' OR ';
            }
            searchTerms+= '("' + con.E_Mail3__c + '")';
        }
        System.debug(searchTerms);
        List<Contact> results=(List<Contact>)[FIND :searchTerms IN EMAIL FIELDS RETURNING Contact(id,Name)][0];
        if(results.size()>0){
            DuplicateEmailFound=true;
        }
    }
    
    Public pagereference SaveContact(){
        try{
            upsert con;
            if(ButtonClicked=='Save'){
                return new ApexPages.StandardController(con).save();
            }else{
                System.debug('Here');
                pagereference pref=new pagereference('/003/e');
                pref.setRedirect(true);
                return pref;
            }
        }catch(exception e){
            return null;
        }
    }
}
public class fetchPicklistOptsController {    
    
  
    //Fetch Contact ID for Update Copntact and set default value contact have by default
    @AuraEnabled 
    public static Contact getContact(String contactId){                      
        Contact con = [SELECT Id,LastName,FirstName,MiddleName,Salutation,Title,AccountId,Classification_Target__c,Classification_Function__c,
                       CurrencyIsoCode,Source__c,Directory__c,Language__c,Chris_FormerStudent__c,Chris_Member__c,LeadSource,AssistantName,
                       AssistantPhone,Birthdate,Chris_PerDu__c,Chris_PersonallyMet__c,Chris_Private__c,Department,Email,E_Mail2__c,E_Mail3__c,Fax,GenerateTask__c,HomePhone,
                       MailingAddress,MailingCity,MailingCountry,MailingCountryCode,MandA_Participant__c,MandA_Program__c,MandA_Student__c,MissingName__c,MobilePhone,
                       OtherAddress,OtherCity,OtherCountryCode,OtherPhone,Parent_Account__c,OtherStreet,OtherState,MailingState,MailingStateCode,ReportsToId,website_user_id__c,
                       Twitter_Name__c,website_user__c,X_Hubspot_CompanyName__c,X_Hubspot_LinkedInBio__c,X_Hubspot_Source__c,X_Hupspot_Title__c FROM Contact where Id =:contactId];
        return con;       
    }
    
    @AuraEnabled
    public static List < String > getselectOptions(sObject objObject, string fld) {
        //system.debug('objObject --->' + objObject);
        //system.debug('fld --->' + fld);
        
        List < String > allOpts = new list < String > ();
        // Get the object type of the SObject.
        Schema.sObjectType objType = objObject.getSObjectType();
        
        // Describe the SObject using its object type.
        Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
        
        // Get a map of fields for the SObject
        map < String, Schema.SObjectField > fieldMap = objDescribe.fields.getMap();
        
        // Get the list of picklist values for this field.
        list < Schema.PicklistEntry > values =
            fieldMap.get(fld).getDescribe().getPickListValues();
        if(fld == 'MailingCountryCode' || fld == 'CurrencyIso'  || fld == 'OtherCountryCode' || fld == 'OtherCountryCode' || fld == 'MailingStateCode' || fld == 'OtherStateCode'){
            for (Schema.PicklistEntry a: values) {
                allOpts.add(a.getLabel());
            }
            
        }
        else{
            // Add these values to the selectoption list.
            for (Schema.PicklistEntry a: values) {
                allOpts.add(a.getValue());
            }
        }
        system.debug('allOpts ---->' + allOpts);
        allOpts.sort();
        return allOpts;
    }
    @AuraEnabled
    public static String fetchAllEmails(String email , String email2 , String email3){
      
        String str = '';
        for(Contact con: [SELECT Email,E_Mail2__c,E_Mail3__c FROM Contact]){
            if(con.email == email && (con.email != null || con.email != '') 
               || email == con.E_Mail2__c && (con.E_Mail2__c != null || con.E_Mail2__c != '')
               || email == con.E_Mail2__c && (con.E_Mail2__c != null || con.E_Mail2__c != '')
               || email == con.E_Mail3__c && (con.E_Mail3__c != null || con.E_Mail3__c != '')){
                   str = 'Email Already Exist!';
                   return str;
               }
        }
        return str;
    }
    
    @AuraEnabled
    public static String commitContact(Contact contactRecord, String updateInsertRecord){                   
        if(updateInsertRecord == 'Update'){
            try {                                  
                update contactRecord;
                return contactRecord.id;
                
            }
            catch(DmlException e) {
                return 'Error: ' + e.getMessage();
            }
        }
        if(updateInsertRecord == 'Insert'){
            try {            
                
                insert contactRecord;
                return contactRecord.id;
                
            }
            catch(DmlException e) {
                return 'Error: ' + e.getMessage();
            }
        }
        return null;
    }
    
    @AuraEnabled
    public static List < sObject > fetchLookUpValues(String searchKeyWord, String ObjectName) {
        system.debug('ObjectName-->' + ObjectName);
        String searchKey = searchKeyWord + '%';
        
        List < sObject > returnList = new List < sObject > ();
        
        // Create a Dynamic SOQL Query For Fetch Record List with LIMIT 5   
        String sQuery =  'select id, Name from ' +ObjectName + ' where Name LIKE: searchKey order by createdDate DESC limit 5';
        List < sObject > lstOfRecords = Database.query(sQuery);
        
        for (sObject obj: lstOfRecords) {
            returnList.add(obj);
        }
        return returnList;
    }
    
    @AuraEnabled 
    public static List<controllingFieldWrapper> getDependentMap(sObject objDetail, string contrfieldApiName,string depfieldApiName) {
        List<controllingFieldWrapper> MainDataControlling=new List<controllingFieldWrapper>();
        
        
        String controllingField = contrfieldApiName.toLowerCase();
        String dependentField = depfieldApiName.toLowerCase();
        
        Map<String,String> objResults = new Map<String,String>();
        
        Schema.sObjectType objType = objDetail.getSObjectType();
        if (objType==null){
            return MainDataControlling;
        }
        
        Map<String, Schema.SObjectField> objFieldMap = objType.getDescribe().fields.getMap();
        
        if (!objFieldMap.containsKey(controllingField) || !objFieldMap.containsKey(dependentField)){
            return MainDataControlling;     
        }
        
        Schema.SObjectField theField = objFieldMap.get(dependentField);
        Schema.SObjectField ctrlField = objFieldMap.get(controllingField);
        
        List<Schema.PicklistEntry> contrEntries = ctrlField.getDescribe().getPicklistValues();
        List<PicklistEntryWrapper> depEntries = wrapPicklistEntries(theField.getDescribe().getPicklistValues());
        List<String> controllingValues = new List<String>();
        
        Map<String,controllingFieldWrapper> ControllingFieldMap=new Map<String,controllingFieldWrapper>();
        
        for (Schema.PicklistEntry ple : contrEntries) {
            objResults.put(ple.getValue(), ple.getLabel());
            controllingValues.add(ple.getValue());
            
            controllingFieldWrapper ControllingFieldWrap=new controllingFieldWrapper();
            ControllingFieldWrap.fieldValue=ple.getValue();
            ControllingFieldWrap.fieldLabel=ple.getLabel();
            ControllingFieldWrap.DependentValues=new List<dependentFieldWrapper>();
            
            ControllingFieldMap.put(ple.getValue(), ControllingFieldWrap);
        }
        
        for (PicklistEntryWrapper plew : depEntries) {
            String validForBits = base64ToBits(plew.validFor);
            
            for (Integer i = 0; i < validForBits.length(); i++) {
                String bit = validForBits.mid(i, 1);
                if (bit == '1') {
                    if(ControllingFieldMap.containsKey(controllingValues.get(i))){
                        
                        dependentFieldWrapper fieldWrap=new dependentFieldWrapper();
                        fieldWrap.fieldLabel=plew.label;
                        fieldWrap.fieldValue=plew.value;
                        
                        ControllingFieldMap.get(controllingValues.get(i)).DependentValues.add(fieldWrap);
                    }
                }
            } 
        } 
        
        for(String Key:ControllingFieldMap.keySet()){
            MainDataControlling.add(ControllingFieldMap.get(Key));
        }
        return MainDataControlling;
    }
    
    public static String decimalToBinary(Integer val) {
        String bits = '';
        while (val > 0) {
            Integer remainder = Math.mod(val, 2);
            val = Integer.valueOf(Math.floor(val / 2));
            bits = String.valueOf(remainder) + bits;
        }
        return bits;
    }
    
    public static String base64ToBits(String validFor) {
        if (String.isEmpty(validFor)) return '';
        
        String validForBits = '';
        
        for (Integer i = 0; i < validFor.length(); i++) {
            String thisChar = validFor.mid(i, 1);
            Integer val = base64Chars.indexOf(thisChar);
            String bits = decimalToBinary(val).leftPad(6, '0');
            validForBits += bits;
        }
        
        return validForBits;
    }
    
    private static final String base64Chars = '' +
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
        'abcdefghijklmnopqrstuvwxyz' +
        '0123456789+/';
    
    
    private static List<PicklistEntryWrapper> wrapPicklistEntries(List<Schema.PicklistEntry> PLEs) {
        return (List<PicklistEntryWrapper>)
            JSON.deserialize(JSON.serialize(PLEs), List<PicklistEntryWrapper>.class);
    }
    
    public class PicklistEntryWrapper{
        public String active {get;set;}
        public String defaultValue {get;set;}
        public String label {get;set;}
        public String value {get;set;}
        public String validFor {get;set;}
        public PicklistEntryWrapper(){            
        }
        
    }
    
    Public Class controllingFieldWrapper{
        @auraEnabled
        Public String fieldValue{get;set;}
        @auraEnabled
        Public String fieldLabel{get;set;}
        @auraEnabled
        Public List<dependentFieldWrapper> DependentValues{get;set;}
    }
    
    Public Class dependentFieldWrapper{
        @auraEnabled
        Public String fieldValue{get;set;}
        @auraEnabled
        Public String fieldLabel{get;set;}
    }
    
}
public class fetchPicklistOptsController {    
    
    /*fetch USser Name*/
    @AuraEnabled 
    public static user fetchUser(){
        User u = [select id,Name from User where id =: userInfo.getUserId()];
        return u;
    }
}
VF page----------------------------
<apex:page controller="editDeleteContactRecords" >
    <apex:form >
        <apex:pageBlock title="Account Detail">
    
        <apex:pageBlockSection >
        <apex:outputField value="{!acc.Name}"/>
        <apex:outputField value="{!acc.Phone}"/>
        <apex:outputField value="{!acc.Fax}"/>
        <apex:outputField value="{!acc.AccountNumber}"/>
        </apex:pageBlockSection>
        
        <apex:pageBlockSection title="Contacts" collapsible="false" columns="1">
        
        
        <apex:pageBlockTable value="{!acts}" var="con">
        
       <apex:column headerValue="Action">
        <apex:commandLink value="Edit |" action="{!editContact}">
        <apex:param value="{!con.Id}" name="selectedContactId" assignTo="{!selectedContact}"/>
        </apex:commandLink>
        <apex:commandLink value="Del" action="{!deleteSelectedContact}">
        <apex:param value="{!con.id}" assignTo="{!delSelContId}" name="delContId"/>
        </apex:commandLink>
        </apex:column>     
        <apex:column value="{!con.Name}"/>
        <apex:column value="{!con.Email}"/>
        <apex:column value="{!con.Title}"/>
        
        </apex:pageBlockTable>
        
       </apex:pageBlockSection>
        
        </apex:pageBlock>
    </apex:form>

</apex:page>


Apex class----------------------------
public class editDeleteContactRecords
{
public Account acc {get;set;}
public Id id;





     public editDeleteContactRecords (){
     
           id  = ApexPages.CurrentPage().getparameters().get('id');
           acc  =  (id==null)?new Account():[select  Name,Phone,fax,AccountNumber From Account where Id =:id];
     
     
     }
     
      public List<Contact> getacts(){
          
          Id id  = ApexPages.CurrentPage().getparameters().get('id');
          List<Contact> acts = [select id,Name,Title,Email,Phone from Contact where AccountId =: id ];
         
          
         return acts;
        
        
          
          // parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
           
       }
     
    
    public PageReference editContact(){
    
     String selectedContact =apexpages.currentPage().getParameters().get('selectedContactId');
    PageReference pg=new PageReference('/'+'apex/UpdateDetail?id='+selectedContact);
    return pg;
        
    }
    // Initialize setCon and return a list of records
     public PageReference deleteSelectedContact(){
     String delSelContId= ApexPages.CurrentPage().getparameters().get('delContId');
       
        if(delSelContId!=null){
        Contact delContact = [Select Id from Contact where Id=:delSelContId];
        delete delContact;
        }
        
        return null;
        
    }  

}
Opportunity
 Objectstaging__c
Fields:
  1. Individual_or_Organization__c (Text)
  2. Organization_Name__c
  3. First_Name__c
  4. Last_Name__c
  5. Postal_Code__c
  6. Date_Recieved__c (Date)
  7. Amount__c (Currency)
  8. Error_Message__c (Long Text)
  9. Description__c
 
Requirement:
 
Case1.  If  Individual_or_Organization__c==I  ,
  • Search for existing contact with matching FistName , LastName and Postal Code. If contact not found then create new contact.
 
  • If staging record contains value in Organization_Name__c  and Postal_Code__c Fields then search for account with matching name and postal code. If account found then link contact record with this account.
 
  • Create new opportunity record for that contact.
Assignment 1. Create Batch Class to Process Stagings and insert Opportunity
 Objectstaging__c
Fields:
  1. Individual_or_Organization__c (Text)
  2. Organization_Name__c
  3. First_Name__c
  4. Last_Name__c
  5. Postal_Code__c
  6. Date_Recieved__c (Date)
  7. Amount__c (Currency)
  8. Error_Message__c (Long Text)
  9. Description__c
 
Requirement:
 
Case1.  If  Individual_or_Organization__c==I  ,
  • Search for existing contact with matching FistName , LastName and Postal Code. If contact not found then create new contact.
 
  • If staging record contains value in Organization_Name__c  and Postal_Code__c Fields then search for account with matching name and postal code. If account found then link contact record with this account.
 
  • Create new opportunity record for that contact.
 
Case2. If  Individual_or_Organization__c==O 
  • Search for existing Account  with matching  Organization_Name__c and Postal Code. If Account not found then create new account.
 
  • If staging record contains value in Last_Name__c and Postal_Code__c  Fields then search for contact with matching firstname,lastname  and postal code. If contact found then link contact record with the  account.
 
  • Create Opportunity record for account
 
Field Mapping for Opportunity:
OpportunityName = Account Name or Contact Name+CloseDate
ColseDate = Date_Recieved__c
Amount = Amount__C
Description=Description__c
 
VF page
<apex:page controller="contactEditDelete" tabStyle="Account">
    <apex:form >
    <apex:pageBlock title="Account Detail">
        <apex:pageBlockSection >
        <apex:outputField value="{!acc.Name}"/>
        <apex:outputField value="{!acc.Phone}"/>
        <apex:outputField value="{!acc.Fax}"/>
        <apex:outputField value="{!acc.AccountNumber}"/>
        </apex:pageBlockSection>
        
       <apex:pageBlockSection title="Contact" collapsible="false" columns="1">
           <apex:pageBlockTable value="{!acts}" var="conts">
               <apex:column headerValue="Action">
               <apex:commandLink value="Edit |" action="{!editRedirect}">
               <apex:param value="{!conts.Id}" name="selectedContactId" assignTo="{!selectedContact}"/>
               </apex:commandLink>
               <apex:commandLink value=" Del"/>
               </apex:column>
               <apex:column value="{!conts.Name}"/>
               <apex:column value="{!conts.Title}"/>
               <apex:column value="{!conts.Email}"/>
           </apex:pageBlockTable>
       </apex:pageBlockSection>
        
     </apex:pageBlock>
    </apex:form>
</apex:page>
    
   Controller
public class contactEditDelete{

public Account acc {get;set;}
public String selectedContact {get;set;}
public String currentRecordId {get;set;}
public String parameterValue {get;set;}


    public contactEditDelete(){
       Id id  = ApexPages.CurrentPage().getparameters().get('id');
       acc  =  (id==null)?new Account():[select  Name,Phone,fax,AccountNumber From Account where Id =:id];
    
        
    }
    public List<Contact> getacts(){
          currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
          List<Contact> acts = [select id,Name,Title,Email,Phone from Contact where AccountId =: currentRecordId ];
          parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
          return acts;
    }
         
    public PageReference editRedirect(){
    selectedContact =apexpages.currentPage().getParameters().get('selectedContactId');
    PageReference pg=new PageReference('/'+selectedContact+'/e');
    return pg;
        
    }
          
}
public with sharing class ContactEditController {
    Public Contact con{get;set;}
    Public Boolean DuplicateEmailFound{get;set;}
    Public String ButtonClicked{get;set;}
    Public ApexPages.StandardController stdController{get;set;}
    public ContactEditController(ApexPages.StandardController controller) {
        stdController=controller;
        con=(Contact)controller.getRecord();
        con.ownerId=userinfo.getUserId();
        DuplicateEmailFound=false;
    }
    
    Public pagereference Cancel(){
        Pagereference pref=stdController.Cancel();
        return pref;
    }
    
    Public Void CheckDuplicateEmail(){
        String searchTerms = '';
        if(String.IsNotBlank(con.Email)){
            searchTerms+= '("' + con.Email + '")';
        }
        
        if(String.IsNotBlank(con.E_Mail2__c)){
            if(!String.isEmpty(searchTerms)){
                searchTerms += ' OR ';
            }

            searchTerms+= '("' + con.E_Mail2__c+ '")';
        }
        
        if(String.IsNotBlank(con.E_Mail3__c)){
            if(!String.isEmpty(searchTerms)){
                searchTerms += ' OR ';
            }
            searchTerms+= '("' + con.E_Mail3__c + '")';
        }
        System.debug(searchTerms);
        List<Contact> results=(List<Contact>)[FIND :searchTerms IN EMAIL FIELDS RETURNING Contact(id,Name)][0];
        if(results.size()>0){
            DuplicateEmailFound=true;
        }
    }
    
    Public pagereference SaveContact(){
        try{
            upsert con;
            if(ButtonClicked=='Save'){
                return new ApexPages.StandardController(con).save();
            }else{
                System.debug('Here');
                pagereference pref=new pagereference('/003/e');
                pref.setRedirect(true);
                return pref;
            }
        }catch(exception e){
            return null;
        }
    }
}
public class fetchPicklistOptsController {    
    
  
    //Fetch Contact ID for Update Copntact and set default value contact have by default
    @AuraEnabled 
    public static Contact getContact(String contactId){                      
        Contact con = [SELECT Id,LastName,FirstName,MiddleName,Salutation,Title,AccountId,Classification_Target__c,Classification_Function__c,
                       CurrencyIsoCode,Source__c,Directory__c,Language__c,Chris_FormerStudent__c,Chris_Member__c,LeadSource,AssistantName,
                       AssistantPhone,Birthdate,Chris_PerDu__c,Chris_PersonallyMet__c,Chris_Private__c,Department,Email,E_Mail2__c,E_Mail3__c,Fax,GenerateTask__c,HomePhone,
                       MailingAddress,MailingCity,MailingCountry,MailingCountryCode,MandA_Participant__c,MandA_Program__c,MandA_Student__c,MissingName__c,MobilePhone,
                       OtherAddress,OtherCity,OtherCountryCode,OtherPhone,Parent_Account__c,OtherStreet,OtherState,MailingState,MailingStateCode,ReportsToId,website_user_id__c,
                       Twitter_Name__c,website_user__c,X_Hubspot_CompanyName__c,X_Hubspot_LinkedInBio__c,X_Hubspot_Source__c,X_Hupspot_Title__c FROM Contact where Id =:contactId];
        return con;       
    }
    
    @AuraEnabled
    public static List < String > getselectOptions(sObject objObject, string fld) {
        //system.debug('objObject --->' + objObject);
        //system.debug('fld --->' + fld);
        
        List < String > allOpts = new list < String > ();
        // Get the object type of the SObject.
        Schema.sObjectType objType = objObject.getSObjectType();
        
        // Describe the SObject using its object type.
        Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
        
        // Get a map of fields for the SObject
        map < String, Schema.SObjectField > fieldMap = objDescribe.fields.getMap();
        
        // Get the list of picklist values for this field.
        list < Schema.PicklistEntry > values =
            fieldMap.get(fld).getDescribe().getPickListValues();
        if(fld == 'MailingCountryCode' || fld == 'CurrencyIso'  || fld == 'OtherCountryCode' || fld == 'OtherCountryCode' || fld == 'MailingStateCode' || fld == 'OtherStateCode'){
            for (Schema.PicklistEntry a: values) {
                allOpts.add(a.getLabel());
            }
            
        }
        else{
            // Add these values to the selectoption list.
            for (Schema.PicklistEntry a: values) {
                allOpts.add(a.getValue());
            }
        }
        system.debug('allOpts ---->' + allOpts);
        allOpts.sort();
        return allOpts;
    }
    @AuraEnabled
    public static String fetchAllEmails(String email , String email2 , String email3){
      
        String str = '';
        for(Contact con: [SELECT Email,E_Mail2__c,E_Mail3__c FROM Contact]){
            if(con.email == email && (con.email != null || con.email != '') 
               || email == con.E_Mail2__c && (con.E_Mail2__c != null || con.E_Mail2__c != '')
               || email == con.E_Mail2__c && (con.E_Mail2__c != null || con.E_Mail2__c != '')
               || email == con.E_Mail3__c && (con.E_Mail3__c != null || con.E_Mail3__c != '')){
                   str = 'Email Already Exist!';
                   return str;
               }
        }
        return str;
    }
    
    @AuraEnabled
    public static String commitContact(Contact contactRecord, String updateInsertRecord){                   
        if(updateInsertRecord == 'Update'){
            try {                                  
                update contactRecord;
                return contactRecord.id;
                
            }
            catch(DmlException e) {
                return 'Error: ' + e.getMessage();
            }
        }
        if(updateInsertRecord == 'Insert'){
            try {            
                
                insert contactRecord;
                return contactRecord.id;
                
            }
            catch(DmlException e) {
                return 'Error: ' + e.getMessage();
            }
        }
        return null;
    }
    
    @AuraEnabled
    public static List < sObject > fetchLookUpValues(String searchKeyWord, String ObjectName) {
        system.debug('ObjectName-->' + ObjectName);
        String searchKey = searchKeyWord + '%';
        
        List < sObject > returnList = new List < sObject > ();
        
        // Create a Dynamic SOQL Query For Fetch Record List with LIMIT 5   
        String sQuery =  'select id, Name from ' +ObjectName + ' where Name LIKE: searchKey order by createdDate DESC limit 5';
        List < sObject > lstOfRecords = Database.query(sQuery);
        
        for (sObject obj: lstOfRecords) {
            returnList.add(obj);
        }
        return returnList;
    }
    
    @AuraEnabled 
    public static List<controllingFieldWrapper> getDependentMap(sObject objDetail, string contrfieldApiName,string depfieldApiName) {
        List<controllingFieldWrapper> MainDataControlling=new List<controllingFieldWrapper>();
        
        
        String controllingField = contrfieldApiName.toLowerCase();
        String dependentField = depfieldApiName.toLowerCase();
        
        Map<String,String> objResults = new Map<String,String>();
        
        Schema.sObjectType objType = objDetail.getSObjectType();
        if (objType==null){
            return MainDataControlling;
        }
        
        Map<String, Schema.SObjectField> objFieldMap = objType.getDescribe().fields.getMap();
        
        if (!objFieldMap.containsKey(controllingField) || !objFieldMap.containsKey(dependentField)){
            return MainDataControlling;     
        }
        
        Schema.SObjectField theField = objFieldMap.get(dependentField);
        Schema.SObjectField ctrlField = objFieldMap.get(controllingField);
        
        List<Schema.PicklistEntry> contrEntries = ctrlField.getDescribe().getPicklistValues();
        List<PicklistEntryWrapper> depEntries = wrapPicklistEntries(theField.getDescribe().getPicklistValues());
        List<String> controllingValues = new List<String>();
        
        Map<String,controllingFieldWrapper> ControllingFieldMap=new Map<String,controllingFieldWrapper>();
        
        for (Schema.PicklistEntry ple : contrEntries) {
            objResults.put(ple.getValue(), ple.getLabel());
            controllingValues.add(ple.getValue());
            
            controllingFieldWrapper ControllingFieldWrap=new controllingFieldWrapper();
            ControllingFieldWrap.fieldValue=ple.getValue();
            ControllingFieldWrap.fieldLabel=ple.getLabel();
            ControllingFieldWrap.DependentValues=new List<dependentFieldWrapper>();
            
            ControllingFieldMap.put(ple.getValue(), ControllingFieldWrap);
        }
        
        for (PicklistEntryWrapper plew : depEntries) {
            String validForBits = base64ToBits(plew.validFor);
            
            for (Integer i = 0; i < validForBits.length(); i++) {
                String bit = validForBits.mid(i, 1);
                if (bit == '1') {
                    if(ControllingFieldMap.containsKey(controllingValues.get(i))){
                        
                        dependentFieldWrapper fieldWrap=new dependentFieldWrapper();
                        fieldWrap.fieldLabel=plew.label;
                        fieldWrap.fieldValue=plew.value;
                        
                        ControllingFieldMap.get(controllingValues.get(i)).DependentValues.add(fieldWrap);
                    }
                }
            } 
        } 
        
        for(String Key:ControllingFieldMap.keySet()){
            MainDataControlling.add(ControllingFieldMap.get(Key));
        }
        return MainDataControlling;
    }
    
    public static String decimalToBinary(Integer val) {
        String bits = '';
        while (val > 0) {
            Integer remainder = Math.mod(val, 2);
            val = Integer.valueOf(Math.floor(val / 2));
            bits = String.valueOf(remainder) + bits;
        }
        return bits;
    }
    
    public static String base64ToBits(String validFor) {
        if (String.isEmpty(validFor)) return '';
        
        String validForBits = '';
        
        for (Integer i = 0; i < validFor.length(); i++) {
            String thisChar = validFor.mid(i, 1);
            Integer val = base64Chars.indexOf(thisChar);
            String bits = decimalToBinary(val).leftPad(6, '0');
            validForBits += bits;
        }
        
        return validForBits;
    }
    
    private static final String base64Chars = '' +
        'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
        'abcdefghijklmnopqrstuvwxyz' +
        '0123456789+/';
    
    
    private static List<PicklistEntryWrapper> wrapPicklistEntries(List<Schema.PicklistEntry> PLEs) {
        return (List<PicklistEntryWrapper>)
            JSON.deserialize(JSON.serialize(PLEs), List<PicklistEntryWrapper>.class);
    }
    
    public class PicklistEntryWrapper{
        public String active {get;set;}
        public String defaultValue {get;set;}
        public String label {get;set;}
        public String value {get;set;}
        public String validFor {get;set;}
        public PicklistEntryWrapper(){            
        }
        
    }
    
    Public Class controllingFieldWrapper{
        @auraEnabled
        Public String fieldValue{get;set;}
        @auraEnabled
        Public String fieldLabel{get;set;}
        @auraEnabled
        Public List<dependentFieldWrapper> DependentValues{get;set;}
    }
    
    Public Class dependentFieldWrapper{
        @auraEnabled
        Public String fieldValue{get;set;}
        @auraEnabled
        Public String fieldLabel{get;set;}
    }
    
}
VF page----------------------------
<apex:page controller="editDeleteContactRecords" >
    <apex:form >
        <apex:pageBlock title="Account Detail">
    
        <apex:pageBlockSection >
        <apex:outputField value="{!acc.Name}"/>
        <apex:outputField value="{!acc.Phone}"/>
        <apex:outputField value="{!acc.Fax}"/>
        <apex:outputField value="{!acc.AccountNumber}"/>
        </apex:pageBlockSection>
        
        <apex:pageBlockSection title="Contacts" collapsible="false" columns="1">
        
        
        <apex:pageBlockTable value="{!acts}" var="con">
        
       <apex:column headerValue="Action">
        <apex:commandLink value="Edit |" action="{!editContact}">
        <apex:param value="{!con.Id}" name="selectedContactId" assignTo="{!selectedContact}"/>
        </apex:commandLink>
        <apex:commandLink value="Del" action="{!deleteSelectedContact}">
        <apex:param value="{!con.id}" assignTo="{!delSelContId}" name="delContId"/>
        </apex:commandLink>
        </apex:column>     
        <apex:column value="{!con.Name}"/>
        <apex:column value="{!con.Email}"/>
        <apex:column value="{!con.Title}"/>
        
        </apex:pageBlockTable>
        
       </apex:pageBlockSection>
        
        </apex:pageBlock>
    </apex:form>

</apex:page>


Apex class----------------------------
public class editDeleteContactRecords
{
public Account acc {get;set;}
public Id id;





     public editDeleteContactRecords (){
     
           id  = ApexPages.CurrentPage().getparameters().get('id');
           acc  =  (id==null)?new Account():[select  Name,Phone,fax,AccountNumber From Account where Id =:id];
     
     
     }
     
      public List<Contact> getacts(){
          
          Id id  = ApexPages.CurrentPage().getparameters().get('id');
          List<Contact> acts = [select id,Name,Title,Email,Phone from Contact where AccountId =: id ];
         
          
         return acts;
        
        
          
          // parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
           
       }
     
    
    public PageReference editContact(){
    
     String selectedContact =apexpages.currentPage().getParameters().get('selectedContactId');
    PageReference pg=new PageReference('/'+'apex/UpdateDetail?id='+selectedContact);
    return pg;
        
    }
    // Initialize setCon and return a list of records
     public PageReference deleteSelectedContact(){
     String delSelContId= ApexPages.CurrentPage().getparameters().get('delContId');
       
        if(delSelContId!=null){
        Contact delContact = [Select Id from Contact where Id=:delSelContId];
        delete delContact;
        }
        
        return null;
        
    }  

}
Opportunity
 Objectstaging__c
Fields:
  1. Individual_or_Organization__c (Text)
  2. Organization_Name__c
  3. First_Name__c
  4. Last_Name__c
  5. Postal_Code__c
  6. Date_Recieved__c (Date)
  7. Amount__c (Currency)
  8. Error_Message__c (Long Text)
  9. Description__c
 
Requirement:
 
Case1.  If  Individual_or_Organization__c==I  ,
  • Search for existing contact with matching FistName , LastName and Postal Code. If contact not found then create new contact.
 
  • If staging record contains value in Organization_Name__c  and Postal_Code__c Fields then search for account with matching name and postal code. If account found then link contact record with this account.
 
  • Create new opportunity record for that contact.
Assignment 1. Create Batch Class to Process Stagings and insert Opportunity
 Objectstaging__c
Fields:
  1. Individual_or_Organization__c (Text)
  2. Organization_Name__c
  3. First_Name__c
  4. Last_Name__c
  5. Postal_Code__c
  6. Date_Recieved__c (Date)
  7. Amount__c (Currency)
  8. Error_Message__c (Long Text)
  9. Description__c
 
Requirement:
 
Case1.  If  Individual_or_Organization__c==I  ,
  • Search for existing contact with matching FistName , LastName and Postal Code. If contact not found then create new contact.
 
  • If staging record contains value in Organization_Name__c  and Postal_Code__c Fields then search for account with matching name and postal code. If account found then link contact record with this account.
 
  • Create new opportunity record for that contact.
 
Case2. If  Individual_or_Organization__c==O 
  • Search for existing Account  with matching  Organization_Name__c and Postal Code. If Account not found then create new account.
 
  • If staging record contains value in Last_Name__c and Postal_Code__c  Fields then search for contact with matching firstname,lastname  and postal code. If contact found then link contact record with the  account.
 
  • Create Opportunity record for account
 
Field Mapping for Opportunity:
OpportunityName = Account Name or Contact Name+CloseDate
ColseDate = Date_Recieved__c
Amount = Amount__C
Description=Description__c
 
VF page
<apex:page controller="contactEditDelete" tabStyle="Account">
    <apex:form >
    <apex:pageBlock title="Account Detail">
        <apex:pageBlockSection >
        <apex:outputField value="{!acc.Name}"/>
        <apex:outputField value="{!acc.Phone}"/>
        <apex:outputField value="{!acc.Fax}"/>
        <apex:outputField value="{!acc.AccountNumber}"/>
        </apex:pageBlockSection>
        
       <apex:pageBlockSection title="Contact" collapsible="false" columns="1">
           <apex:pageBlockTable value="{!acts}" var="conts">
               <apex:column headerValue="Action">
               <apex:commandLink value="Edit |" action="{!editRedirect}">
               <apex:param value="{!conts.Id}" name="selectedContactId" assignTo="{!selectedContact}"/>
               </apex:commandLink>
               <apex:commandLink value=" Del"/>
               </apex:column>
               <apex:column value="{!conts.Name}"/>
               <apex:column value="{!conts.Title}"/>
               <apex:column value="{!conts.Email}"/>
           </apex:pageBlockTable>
       </apex:pageBlockSection>
        
     </apex:pageBlock>
    </apex:form>
</apex:page>
    
   Controller
public class contactEditDelete{

public Account acc {get;set;}
public String selectedContact {get;set;}
public String currentRecordId {get;set;}
public String parameterValue {get;set;}


    public contactEditDelete(){
       Id id  = ApexPages.CurrentPage().getparameters().get('id');
       acc  =  (id==null)?new Account():[select  Name,Phone,fax,AccountNumber From Account where Id =:id];
    
        
    }
    public List<Contact> getacts(){
          currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
          List<Contact> acts = [select id,Name,Title,Email,Phone from Contact where AccountId =: currentRecordId ];
          parameterValue = ApexPages.CurrentPage().getparameters().get('nameParam');
          return acts;
    }
         
    public PageReference editRedirect(){
    selectedContact =apexpages.currentPage().getParameters().get('selectedContactId');
    PageReference pg=new PageReference('/'+selectedContact+'/e');
    return pg;
        
    }
          
}