• sumit sharma 200
  • NEWBIE
  • 190 Points
  • Member since 2017

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 42
    Questions
  • 57
    Replies
User-added image

This is my detail page and when i click on skip to milestone it will open a visual force page which looks like below

User-added image

How can i remove the extra portions like setup in the head part?

the button code for skip to milestone is

{!REQUIRESCRIPT("/xdomain/xdomain.js")}
{!REQUIRESCRIPT("/soap/ajax/39.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/39.0/apex.js")}
{!REQUIRESCRIPT("/support/console/39.0/integration.js")}

var status='{!Program_Member_MVN__c.Status_MVN__c}';
var PmId='{!JSENCODE(Program_Member_MVN__c.Id)}'; 
var url;
if (sforce.console.isInConsole()) {
if(status == 'On Therapy')
{
url = "/apex/Milestone_skip?id="+PmId;
window.open(url,'_blank','toolbar=0,location=0,menubar=0'); 
}  
else
{
alert("Patient must be ‘On-Therapy’ before skipping to a milestone");
}
}

var showTabId = function showTabId(thisVal) {
  sforce.console.refreshPrimaryTabById(thisVal.id, true, '');
};
if (sforce.console != null && sforce.console.isInConsole()) {
    setTimeout(function(){ 
  sforce.console.getFocusedPrimaryTabId(showTabId);
},9500);
}

i am just referring the visual force page link in the button how can modify it show only my visual force part?
When I eneter User name and Date in the input fields then click on login button , it should check whether that User name which Iam referring to last name in lead and that date of birth  is present in the Lead. If its present then it should Login and redirect to a visualforce page. Its working fine if iam doing without date when when Iam querying date its throwing the Null pointer exceptio, Attempt to reference null object error. I think its error in the query.Date should be converted in hh:mm:ss i guess please help.

Please  find the code.

public with sharing class LoginCntrl {
    public string userName{get;set;}
   public Lead Dateofbirth{get;set;}
   
  
    public pageReference doLogin() {
         
        if(String.isBlank(userName)) return null;  
        
        string dateformat;
        
        
        
              
        List<Lead> conls = [select id, lastname from Lead where LastName = :userName and date_of_birth__c=:Dateofbirth.Date_of_Birth__c];
        system.debug('dddddddddddddddddd'+conls );
        if(conls.size() == 1 ) {
            return new pageReference('/apex/studentpersonaldetails');
        }
        else {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please Enter correct User Name or Date of Birth'));

        userName = null;
        Dateofbirth = null;
            return null;
        
        }
        
    }

}

VF :-

<apex:page controller="LoginCntrl" showHeader="false" sidebar="false">
    <apex:form >
        <apex:image id="theImage" value="{!$Resource.nmims2}" width="350" height="60"/><br/>

    <apex:pageBlock title="Login Page" >
    <apex:pageMessages ></apex:pageMessages>

    <br/>

      User Name :  <apex:inputtext value="{!userName}"/> <br/>
       <br/>Date of birth: <apex:inputfield value="{!Dateofbirth.Date_of_Birth__c}"/><br/>
       <br/>
    
        <apex:commandButton style="margin-left:10px" value="Login" action="{!doLogin}"/>
</apex:pageBlock>
    </apex:form>
</apex:page>

 
If we select a particular picklist value  for a field status_of_candidate ='Selected'  in "Interviewing candidates" object then the record should be automatically created in another object which is "selected candidates" using name,email and phone values. These both objects are not related to each other through look up or Master detail. Please find the below code.

trigger ifselectedcreaterecordonsc on Interviewing_Candidates__c (before insert, before update) {

list<Interviewing_Candidates__c > Sel = [select id,name, Candidate_Email__c,Status_Of_Candidate__c,c.Candidate_Phone__c from Interviewing_Candidates__c ];

list<selected_candidates__C> lst = new list<selected_candidates__C>();

for(Interviewing_Candidates__c c : sel){

if(c.Status_Of_Candidate__c == 'Selected'){

selected_candidates__C ss = new selected_candidates__C();

ss.name = c.name;
ss.Email__c =c.Candidate_Email__c;
ss.phone__C =c.Candidate_Phone__c;
 insert c;

}

}

}

Need your help
Please find the code :-
<apex:page standardcontroller="Contact" sidebar="false" extensions="sendofferlettercontroller" >
  <apex:form >

  <apex:pageBlock title="Send Offer Letter">
      <p style="text-align: center; font-size: 18px; background-color: #d0e4fe;">Send An Email Attaching Impact Guru Offer Letter</p>
<apex:pageBlockSection >
                        <apex:inputText id="email" label="TO : "  Style="width:300px;" value="{!toEmail}"/><br/>
                        <apex:inputText id="ccEmail" label="CC : "  Style="width:300px;" value="{!ccEmail}"/><br/>

                                             <apex:inputTextarea id="Subject" label="Subject : "  Style="width:300px;" value="{!subject}" cols="80"/><br/>

                       <apex:inputTextarea id="Body" label="Body : "  Style="width:300px;" value="{!body}" rows="10" cols="80"/><br/>

                        
            
                        
            <apex:commandButton value="Send Email" action="{!sendEmail}"  />
            <apex:commandButton value="Cancel" action="{!cancel}"/> 

        </apex:pageBlockSection>
                              <apex:iframe src=".apex/offerletterpage?id={!parentid}"/>


    </apex:pageBlock>
            </apex:form>

</apex:page>

----------------------------

public class sendofferlettercontroller {

   public sendofferlettercontroller() { }

    public String toEmail {get;set;}
        public String ccEmail {get;set;}
    Public ID ParentID{get;set;}

    public String subject {get;set;}
    public String body {get;set;}
        
    private final contact MyLead;
       public static contact co1{get;set;}

    
    public sendofferlettercontroller(ApexPages.StandardController controller)
    {
        this.MyLead=(Contact)controller.getRecord();
             ParentID = apexpages.currentpage().getparameters().get('id');

    } 
   
             
    public PageReference sendEmail() {
        
           co1 = [select id ,name, Email  from contact where id =: ApexPages.currentPage().getParameters().get('id')];

        //create a mail object to send email 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        String[] toaddress = toEmail.Split(','); //using comma separator between emails
        //String[] toaddress = toEmail.Split('[,;]'); //use can use Regex to mix with comma & semi colon separator

        //email properties
        String[] ccaddress = ccEmail.Split(',');
        mail.setToAddresses(toaddress);
        mail.setSubject(subject);
                           mail.setccAddresses(ccaddress);  

        mail.setUseSignature(true);
        mail.setPlainTextBody(body); 
                
        // send the email'
                             PageReference pdf =  Page.offerletterpage;
                                                  pdf.getParameters().put('id',(String)co1.id);
                     pdf.setRedirect(true);
                                          blob b;

                     try{
                     b = pdf.getContent();
                     }catch (VisualforceException e){
                     b = Blob.valueOf('Some Text');
                     }
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
                     efa.setFileName('ImpactGuru Offer Letter PDf'+'.pdf');
                     efa.setBody(b);
                     mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
                       try
                    {
                 //   Messaging.SendEmailResult[] resultMail = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                    catch(System.EmailException ex)
                    {
                    }
                    Datetime myDatetime = Datetime.now();
                    String myDatetimeStr;  
                    Attachment a = new Attachment();
                    a.parentid = co1.id;
                    a.body = b;
                    a.name = (co1.Name+' - '+myDatetime.format('d - MMMM, yyyy'));
                    insert a;

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        Return Page.sendofferletter;

     }   
   

}
public class sendofferlettercontroller {

   public sendofferlettercontroller() { }

    public String toEmail {get;set;}
        public String ccEmail {get;set;}
    Public ID ParentID{get;set;}

    public String subject {get;set;}
    public String body {get;set;}
        
    private final contact MyLead;
       public static contact co1{get;set;}

    
    public sendofferlettercontroller(ApexPages.StandardController controller)
    {
        this.MyLead=(Contact)controller.getRecord();
             ParentID = apexpages.currentpage().getparameters().get('id');

    } 
   
             
    public PageReference sendEmail() {
        
           co1 = [select id ,name, Email  from contact where id =: ApexPages.currentPage().getParameters().get('id')];

        //create a mail object to send email 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        String[] toaddress = toEmail.Split(','); //using comma separator between emails
        //String[] toaddress = toEmail.Split('[,;]'); //use can use Regex to mix with comma & semi colon separator

        //email properties
        String[] ccaddress = ccEmail.Split(',');
        mail.setToAddresses(toaddress);
        mail.setSubject(subject);
                           mail.setccAddresses(ccaddress);  

        mail.setUseSignature(true);
        mail.setPlainTextBody(body); 
                
        // send the email'
                             PageReference pdf =  Page.offerletterpage;
                                                  pdf.getParameters().put('id',(String)co1.id);
                     pdf.setRedirect(true);
                                          blob b;

                     try{
                     b = pdf.getContent();
                     }catch (VisualforceException e){
                     b = Blob.valueOf('Some Text');
                     }
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
                     efa.setFileName('ImpactGuru Offer Letter PDf'+'.pdf');
                     efa.setBody(b);
                     mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
                       try
                    {
                 //   Messaging.SendEmailResult[] resultMail = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                    catch(System.EmailException ex)
                    {
                    }
                    Datetime myDatetime = Datetime.now();
                    String myDatetimeStr;  
                    Attachment a = new Attachment();
                    a.parentid = co1.id;
                    a.body = b;
                    a.name = (co1.Name+' - '+myDatetime.format('d - MMMM, yyyy'));
                    insert a;

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        Return Page.sendofferletter;

     }   
   

}

Thanks in advance
Hello friends, I want to add Multiple email address for sending the email in To: input box, but it doesnot accept more than one. Do anyone know how to solve this.
Please find the code below

public class sendemailtestcontroller {

    public sendemailtestcontroller() {

    }





    public String toEmail {get;set;}
    public String subject {get;set;}
    public String body {get;set;}
    
    
    private final Lead MyLead;
    public sendemailtestcontroller(ApexPages.StandardController controller)
    
   
    {
        this.MyLead=(Lead)controller.getRecord();
    } 
   
             
    public void sendEmail() {
        
        //create a mail object to send email 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        String[] toaddress = (new String[]{toEmail});
        
        //email properties
        mail.setToAddresses(toaddress);
        mail.setSubject(subject);
        mail.setUseSignature(true);
        mail.setPlainTextBody(body); 
               
        // send the email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }   
   

}

Vf :
<apex:page standardcontroller="Lead" extensions="sendemailtestcontroller">
  <apex:pageBlock title="EMAIL TEST">
        <apex:form >
        <br />
            <apex:outputLabel value="To" for="To"/>:<br/>
            <apex:inputText value="{!toEmail}" id="email"/><br/><br/>
                        
            <apex:outputLabel value="Subject" for="Subject"/>:<br />     
            <apex:inputTextarea value="{!subject}" id="Subject" cols="80" /><br/><br/>
                        
            <apex:outputLabel value="Body" for="Body"/>:<br />     
            <apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/><br/><br/>      
            <br /><br />
                        
            <apex:commandButton value="Send Email" action="{!sendEmail}"  />
            <apex:commandButton value="Cancel" action="{!cancel}"/> 
        
        </apex:form>
    </apex:pageBlock>
</apex:page>

User-added image
User-added image

I want to implement similar button on Account where I select the List view and based on which I select the select all check box or select a specific set of records to click on change owner and change the owner of records

I have implemented a similar functionality, the only problem is  I need to add a select all check box at the top and when i chick on chage owner button it should get the owner id's of selected records and update it to the new owner and it should get only those records which are displayed based on list views.eg This Week record list view or last week record list view etc;
Please find the image of what I have Implemented
User-added image
Controller :-
public with sharing class AccountController1 {

    public AccountController1(ApexPages.StandardController controller) {

    }
    
    public List<Account> acc{get;set;}
   public AccountController1(ApexPages.StandardSetController controller1) 
{
        controller1.setPageSize(10);
        acc = new List<Account>();
        acc =  [Select Id,Name,Ownerid,(Select Id,name From contacts) From Account];


}
    public PageReference save(){
     update acc;

     return null;

    
    }

public void changeowner(){



}
}
Page :-
<apex:page standardController="Account" extensions="AccountController1"  recordSetVar="accounts">
<apex:form >
<apex:pageBlock mode="inlineEdit">
<apex:commandButton action="{!save}" value="save"/>
<apex:commandButton action="{!changeowner}" value="Change owner"/>
<apex:pageBlockSection >
<apex:pageBlockTable value="{!acc}" var="a" border="1">
<apex:column >
<Apex:inputCheckbox />
</apex:column>
<apex:column value="{!a.name}" style="padding:20px"/>
<apex:column headerValue="Contact Names" >
        <apex:pageBlockTable value="{!a.contacts}" var="con"  >       
<apex:column value="{!con.Name}" rendered="{!if(con.name!='null',true,false)}" />

</apex:pageblocktable>
</apex:column>
<apex:column headerValue="Owner Name">
 <apex:inputField value="{!a.ownerid}" />

        </apex:column> 
</apex:pageblocktable> 

</apex:pageBlockSection>
</apex:pageBlock>

</apex:form>
  
</apex:page>
 
Hello friends, Iam getting error "Variable does not exist: RecursiveTriggerHandler" while deploying the apex trigger to production.
Please find the trigger below

trigger BD_AccountTrigger on Account (after insert, after update) {
  BD_ProcessSwitchSettings__c custSettings = BD_ProcessSwitchSettings__c.getInstance();
 
 System.debug('****************in BD_LeadTrigger');
 
 if(trigger.isInsert || trigger.isUpdate){
   System.debug('****************in BD_LeadTrigger, Trigger.old:'+trigger.old);
   System.debug('****************in BD_LeadTrigger, Trigger.new:'+trigger.new);
 } 
  
 // if(!custSettings.BD_AllTriggersDisabled__c && custSettings.BD_NotesTriggerEnabled__c){
  if(!custSettings.BD_AllTriggersDisabled__c ){
     if(RecursiveTriggerHandler.isFirstTime){
        RecursiveTriggerHandler.isFirstTime = false;
        new  AC_AccountTriggerHandler().run();
     } 
        
  }
}
Apex class :
trigger updatePhoneAndEmailOnAcc on Contact (after update) {
    map<id,contact> accidVSContact = new map<id, contact>();
    for(contact c1: trigger.new) {
        if(Trigger.newMap.get(c1.id).Email != Trigger.oldMap.get(c1.id).Email || 
            Trigger.newMap.get(c1.id).MobilePhone != Trigger.oldMap.get(c1.id).MobilePhone) {
        
            accidVSContact.put(c1.AccountId, c1); 
        }
    }
    system.debug('accidVSContact:::'+accidVSContact);
    List<account> accls = [select id, Created_By_Email__c, Mobile_Number__c from account where id  IN :accidVSContact.keySet()];
    system.debug('accls:::'+accls);
    for(account a1 :accls) {
        
        a1.Created_By_Email__c = accidVSContact.get(a1.id).Email;
        system.debug('a1.Created_By_Email__c:::'+a1.Created_By_Email__c);
        system.debug('accidVSContact.get(a1.id).Email:::'+accidVSContact.get(a1.id).Email);
 
        a1.Mobile_Number__c = accidVSContact.get(a1.id).MobilePhone ;        
        system.debug('a1.Mobile_Number__c:::'+a1.Mobile_Number__c);
        system.debug('accidVSContact.get(a1.id).MobilePhone:::'+accidVSContact.get(a1.id).MobilePhone);
    }
    system.debug('accls:::'+accls);
    //&& !trigger.isExecuting
    if(accls.size()>0) {
        system.debug('herrer!!!!');
        try {
            update accls;
        } catch(exception e) {system.debug('error::'+e);}
        system.debug('accls!!!'+accls); 
    }

Test class:
@istest
public class updatePhoneAndEmailOnAcc_test{

static testmethod void mm(){

Account ac = new Account (Name = 'Test Account123_1', Campaigner_Name__c = 'Ab_c12',Created_By_Email__c='test@abc.com',Mobile_Number__c ='9999999999');
        insert ac;
 Contact contact = new Contact (FirstName = 'Test', LastName = 'Contact');
      contact.accountid =ac.id;
        insert contact;
   list<account> aa =[select id,Created_By_Email__c from account where id =: ac.id];     

}


}
public class BD_LeadTriggerHandler extends BD_TriggerHandler {

/*
*Author: Vivek
*Date: 01/13/2018
*Description: Defining Constructor
*/  
 public BD_LeadTriggerHandler(){}

/*
*Author: Vivek
*Date: 01/13/2018
*Description: Event handling methods
*/  
  public override void afterUpdate() {
    callAfterUpdateLogic();
  }
  
  public override void afterInsert() {
    callAfterInsertLogic();
  }
  
  public override void beforeUpdate() {
    callBeforeUpdateLogic();
  }
  
  public override void beforeInsert() {
    callBeforeInsertLogic();
  }


/*
*Author: Vivek
*Date: 01/13/2018
*Description: Methods called by Event handling methods which holds actual logic
*/ 
  public void callAfterUpdateLogic(){
    syncLeadRecordsWithBE(trigger.newMap.KeySet(),false);
  }
  
  public void callAfterInsertLogic(){
    syncLeadRecordsWithBE(trigger.newMap.KeySet(),true); 
  }
  
  public void callBeforeUpdateLogic(){
    //Add logic here
  }
  
  public void callBeforeInsertLogic(){
    //Add logic here
  }

/*
*Author: Vivek
*Date: 01/27/2018
*Description: Methods to handle synching functionality with backend in chunks
*/
public static List<Schema.FieldSetMember> getFields() {
        return SObjectType.Lead.FieldSets.BD_LeadIntegrationFields.getFields();
}

private static list<Lead> getLeadRecs(set<id> leadIds) {
    String query = 'SELECT ';
    for(Schema.FieldSetMember f : getFields()) {
            query += f.getFieldPath() + ', ';
    }
    query += ' Owner.Name FROM Lead WHERE ID IN: leadIds';
    return Database.query(query);
}

@future (callout=true)
public static void syncLeadRecordsWithBE(set<id> leadIds, Boolean isInsrt){
 BD_InterfaceConfigParameters__c serviceSettings;
 map<integer,list<Lead>> leadmap = new map<integer,list<Lead>>();
 if(leadIds != NULL){
    list<Lead> leadLst = getLeadRecs(leadIds);
    serviceSettings = BD_InterfaceConfigParameters__c.getValues(system.label.BD_INTERFACE_LeadRequest);
    integer chnkSize = serviceSettings != NULL && serviceSettings.BD_BatchSize__c != NULL && serviceSettings.BD_BatchSize__c < 50.0 
                       ? integer.valueOf(serviceSettings.BD_BatchSize__c) : 50;
    
    
    if(leadLst != NULL){
      integer cnt = 1;
      integer lpcnt = 1;  
      for(Lead ld: leadLst){
        
        if(lpcnt>chnkSize){
           cnt++;
           lpcnt = 1;
        }
        
        if(leadmap.containsKey(cnt)){
            leadmap.get(cnt).add(ld);
        }else{
              leadmap.put(cnt,new list<Lead>{ld}); 
        }
        lpcnt++;
          
      }
        system.debug('**********in Lead trigger, number of chunks:'+leadmap.size());
        system.debug('**********in Lead trigger, Leads in chunks:'+leadMap);
        
        if(!leadMap.isEmpty() && leadMap.size() < 100){
           for(integer i: leadMap.Keyset()){
             system.debug('**********in Lead trigger, in loop, calling service for chunk:'+i);
             BD_VO.LeadResults res = isInsrt ? new BD_GenIntegrationHelper().callObjectInsertSyncService(leadMap.get(i)) : new BD_GenIntegrationHelper().callObjectUpdateSyncService(leadMap.get(i));
           }
        }
    }   
 }
   

}
  

}

written test class :-
@isTest
private class BD_LeadTriggerHandler_Test {
     @isTest static void testAccountServicesLead() {
        
        Lead ld = new Lead();
        ld.lastName = 'Tulsani';
        ld.FirstName = 'Test';
        ld.status = 'New';
        ld.Email='Test@gmail.com';
        ld.phone='12345';
        ld.Mobilephone='12345';
        ld.company='Test comp';
        ld.Title='Test title';
        
        insert ld;
         
        Test.startTest();
        BD_LeadTriggerHandler l1 = new BD_LeadTriggerHandler();
       // l1.afterUpdate();
        l1.beforeUpdate();
        update ld;
        l1.beforeInsert();   
        //AccountService


        Test.stopTest();   
         
    }
}
global class BatchLeadtUpdate implements Database.Batchable<sObject>, Database.AllowsCallouts{
    global Database.QueryLocator start(Database.BatchableContext BC) {
    Date myDate = date.newinstance(2018, 5, 1);
Date myDate2 = date.newinstance(2018, 7, 31);
        String query = 'Select name,id from Lead where CreatedDate>: myDate and CreatedDate <:  myDate2';
        system.debug('Records in this query'+Query);
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
  
        List<Lead> leadls = (List<Lead>)scope; 
        for (lead l1 : leadls) {
            set<id> leadIds = new set<id>();
            leadIds.add(l1.id);
            BD_LeadTriggerHandler.syncLeadRecordsWithBENew(leadIds, false);
            l1.Batch_Updated__c = false;
        }
        update leadls;
    }   
    global void finish(Database.BatchableContext BC) {
    }
}
/*
*Author: Vivek
*Date: 01/05/2018
*Description: Generic Domian Layer methods for SOQL/DML operations
*/
//TODO: add method headers
public virtual class AC_GenericDomainUtility{

//inserting sObjects
public list<sObject> insertSObjectLst(list<sObject> sObjLst){

        try{
            
            Database.insert(sObjLst);
            system.debug('*********in BD_ApplicationDomain, insert success, returning :'+sObjLst);
            return sObjLst;
        
        }catch(exception ex){
          //log exceptions in log object
          system.debug('*********Exception in BD_ApplicationDomain:'+ex.getMessage());
          //throw ex;
   
        }
        return Null;
        

}//insertSObjectLst


//updating sObjects
public list<sObject> updateSObjectLst(list<sObject> sObjLst){

        try{
            
            Database.update(sObjLst);
            system.debug('*********in BD_ApplicationDomain, update success, returning :'+sObjLst);
            return sObjLst;
        
        }catch(exception ex){
          //log exceptions in log object
          system.debug('*********Exception in BD_ApplicationDomain:'+ex.getMessage());
          //throw ex;
        }
        
        return Null;

}//updateSObjectLst

//fetching structure of all fields for respective object
public static string retrieveFieldLstForObject(String SobjectApiName){
        
        string query = '';
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();
 
        String commaSepratedFields = '';
        for(String fieldName : fieldMap.keyset()){
            if(commaSepratedFields == null || commaSepratedFields == ''){
                commaSepratedFields = fieldName;
            }else{
                commaSepratedFields = commaSepratedFields + ', ' + fieldName;
            }
        }
 
        query = BD_InterfaceConstants.SELECTSTR +BD_InterfaceConstants.SPACE+ commaSepratedFields +BD_InterfaceConstants.SPACE+ BD_InterfaceConstants.FROMSTR+ BD_InterfaceConstants.SPACE + SobjectApiName ;
 
        return query;
        



//Fetching error codes for respective Service name and sending map<ErrorCode,Description>
public map<string,string> retrieveServiceErrorCodes(string servName){
   
   map<string,string> retMap = new map<string,string>();
   try{
     
     list<BD_GlobalErrorCodes__c> custLst = BD_GlobalErrorCodes__c.getAll().values();
     
     for(BD_GlobalErrorCodes__c cd: custLst){
       if(cd.BD_ServiceName__c.equals(servName)){
         retMap.put(cd.BD_ErrorCode__c,cd.BD_Description__c);
       }
     }
     
   }catch(Exception ex){
      //log ex
      system.debug('*********exception in BD_GenericDomainUtility.retrieveServiceErrorCodes:'+ex.getMessage());
   }
   
   return retMap;
}  

}

Thanks
/*
*Author: Vivek
*Date: 01/05/2018
*Description: Generic Domian Layer methods for SOQL/DML operations
*/
//TODO: add method headers
public virtual class AC_GenericDomainUtility{

//inserting sObjects
public list<sObject> insertSObjectLst(list<sObject> sObjLst){

        try{
            
            Database.insert(sObjLst);
            system.debug('*********in BD_ApplicationDomain, insert success, returning :'+sObjLst);
            return sObjLst;
        
        }catch(exception ex){
          //log exceptions in log object
          system.debug('*********Exception in BD_ApplicationDomain:'+ex.getMessage());
          //throw ex;
   
        }
        return Null;
        

}//insertSObjectLst


//updating sObjects
public list<sObject> updateSObjectLst(list<sObject> sObjLst){

        try{
            
            Database.update(sObjLst);
            system.debug('*********in BD_ApplicationDomain, update success, returning :'+sObjLst);
            return sObjLst;
        
        }catch(exception ex){
          //log exceptions in log object
          system.debug('*********Exception in BD_ApplicationDomain:'+ex.getMessage());
          //throw ex;
        }
        
        return Null;

}//updateSObjectLst

//fetching structure of all fields for respective object
public static string retrieveFieldLstForObject(String SobjectApiName){
        
        string query = '';
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();
 
        String commaSepratedFields = '';
        for(String fieldName : fieldMap.keyset()){
            if(commaSepratedFields == null || commaSepratedFields == ''){
                commaSepratedFields = fieldName;
            }else{
                commaSepratedFields = commaSepratedFields + ', ' + fieldName;
            }
        }
 
        query = BD_InterfaceConstants.SELECTSTR +BD_InterfaceConstants.SPACE+ commaSepratedFields +BD_InterfaceConstants.SPACE+ BD_InterfaceConstants.FROMSTR+ BD_InterfaceConstants.SPACE + SobjectApiName ;
 
        return query;
        



//Fetching error codes for respective Service name and sending map<ErrorCode,Description>
public map<string,string> retrieveServiceErrorCodes(string servName){
   
   map<string,string> retMap = new map<string,string>();
   try{
     
     list<BD_GlobalErrorCodes__c> custLst = BD_GlobalErrorCodes__c.getAll().values();
     
     for(BD_GlobalErrorCodes__c cd: custLst){
       if(cd.BD_ServiceName__c.equals(servName)){
         retMap.put(cd.BD_ErrorCode__c,cd.BD_Description__c);
       }
     }
     
   }catch(Exception ex){
      //log ex
      system.debug('*********exception in BD_GenericDomainUtility.retrieveServiceErrorCodes:'+ex.getMessage());
   }
   
   return retMap;
}  

}
Hi Friends, when Iam converting leads, its converted into Account and contact.I have one more trigger on account with the field 
contact_associated__C which is the lookup to contact. When account is created it checks if contact_associated__C is null,
if its null, then it takes( name, email and phone) from account and creates a contact and that is associated with 
this contact_associated__C. But now the problem is when Iam converting the lead , its creating account and contact,
 the trigger which i have written on Account fires and associates that contact with  contact_associated__C, 
 but i want that the contact which is coming when lead is converted should be associated with contact_associated__C. 
 but this is not happening . Please find the code below.
 
 trigger updateFundraiser on Account (before insert, before update, after insert) {
    List<contact> newConls = new List<contact>();
    if(Trigger.isUpdate && Trigger.isBefore ) {
        set<id> conIds = new set<id>(); 
        for(account a1: trigger.new) {
            if(a1.Contact_Associated__c != null) {
                conIds.add(a1.Contact_Associated__c);
            }
        }
        system.debug('conIds::'+conIds);
        map<id,contact> conMap = new map<id,contact>([select id, Name, Beneficiary_Name__c,Email, MobilePhone from contact where id IN :conIds]);
        system.debug('conMap::'+conMap);
        for(account a1:trigger.new){
            system.debug('a1.Contact_Associated__c::'+a1.Contact_Associated__c);
            system.debug('!!!!!!'+trigger.oldMap.get(a1.id).Contact_Associated__c);
            //if(a1.Contact_Associated__c != trigger.oldMap.get(a1.id).Contact_Associated__c) {
                system.debug('herere!!!');
                if(a1.Contact_Associated__c != null){
                    a1.Mobile_Number__c = conMap.get(a1.Contact_Associated__c).MobilePhone;
                    a1.Created_By_Email__c = conMap.get(a1.Contact_Associated__c).Email;   
                    a1.Name = conMap.get(a1.Contact_Associated__c).Name;   
    
                    system.debug('herere!!!');
                    system.debug('a1'+a1);  
                } 
            //}
        }
    } 
    // second part 
    // for after insert
    system.debug('here!!!');
    if(Trigger.isAfter && Trigger.isInsert) {
        system.debug('here!!!'+trigger.new);
        for(account a1:trigger.new){
            if(a1.Contact_Associated__c == null || a1.contacts.size() < 0) {
                if(a1.Lead_Converted__c == false) {
                    contact c1 = new contact();
                    c1.Beneficiary_Name__c = a1.Name;
                    c1.LastName = a1.Name;   
                    c1.Email = a1.Created_By_Email__c;
                    c1.MobilePhone = a1.Mobile_Number__c;
                    c1.AccountId = a1.id;
                    newConls.add(c1);
                }
               
            }
        }
        if(newConls.size()>0) {
            insert newConls;
        }
    }
    // for after update
    // updating account associated Ids 
    set<id> conIds = new set<id>();
    map<id,id> accIdsVsConIds = new map<id, id>();
    for(contact c1: newConls) {
        accIdsVsConIds.put(c1.AccountId, c1.id);
    }
    List<account> accToUpdate = [select id, Contact_Associated__c from account where id IN : accIdsVsConIds.keyset()]; 
    for(account a1: accToUpdate) {
        a1.Contact_Associated__c = accIdsVsConIds.get(a1.id);   
    }
    system.debug('accToUpdate::'+accToUpdate);
    update accToUpdate;
}
Need to send data from salesforce to Phpmyadmin in json format. I have endpoint URL , username and Password and all the details. I want to do it with REST integration. There is alredy an integration with Lead with phpmyadmin. when we create a lead , its getting created in PHPmyadmin also. I need to do it same for account and contact.But the code is very complicated unable to understand. Is there a Easy process to send data in Json format.

Any help will be appreciated. Thanks
Hi Friends, I have created a workflow rule In which Iam sending email alerts to recipient based on status. If status is "hot" the 
email alert is firing. But the reqirement is that particular lead URL also should be sent in the email,so that they
can easily click on that link and open that lead easily.
Need help. Thanks
hi friends, When I create a record in an object which I named as Field Team with the values (Name,Email and mobile) 
a record is being created in lead  in the same (Name, Email and mobile) fields. I have achieved it using process builder.
 but when I updating any values from these its not getting updated. can you tell me how can this be achieved. can you help me
with the trigger?
trigger AssignToFirstOwnerForDuplicteLeads on Lead (before insert, before update) {
    set <string> newEmaiSet = new set<string>();
    set<string> newPhNumSet = new set<string>();
    for(lead l1: trigger.new) {
        if(l1.Email != null) {
            newEmaiSet.add(l1.Email);
        }
        if(l1.phone != null) {
            newPhNumSet.add(l1.phone);
        }
    }
    List<lead> leadWithMatchingEmail = new List<lead>();
    if (Trigger.isUpdate) {
        leadWithMatchingEmail = [select id, email, OwnerId from lead where email in :newEmaiSet and Id NOT IN:trigger.newMap.keyset()];
    }
    if (Trigger.isInsert) {
        leadWithMatchingEmail = [select id, email, OwnerId from lead where email in :newEmaiSet];
    }
   // List<lead> leadWithMatchingPhone = [select id, phone, OwnerId from lead where email in :newPhNumSet];
    Map<string, id> emailVSId = new Map<string, id>();
    Map<string, id> phoneVSId = new Map<string, id>();
    for(lead l1: leadWithMatchingEmail) {
        emailVSId.put(l1.Email, l1.OwnerId);
        
    }
    for(lead l1: trigger.new) {
        if(emailVSId.containsKey(l1.Email)) {
            l1.OwnerId = emailVSId.get((l1.Email));
        }
        //  if(phoneVSId.containsKey(l1.phone)) {
        //      l1.OwnerId = phoneVSId.get((l1.phone));
        //   }
        system.debug('l1::@@'+l1);
    }
}
When I eneter User name and Date in the input fields then click on login button , it should check whether that User name which Iam referring to last name in lead and that date of birth  is present in the Lead. If its present then it should Login and redirect to a visualforce page. Its working fine if iam doing without date when when Iam querying date its throwing the Null pointer exceptio, Attempt to reference null object error. I think its error in the query.Date should be converted in hh:mm:ss i guess please help.

Please  find the code.

public with sharing class LoginCntrl {
    public string userName{get;set;}
   public Lead Dateofbirth{get;set;}
   
  
    public pageReference doLogin() {
         
        if(String.isBlank(userName)) return null;  
        
        string dateformat;
        
        
        
              
        List<Lead> conls = [select id, lastname from Lead where LastName = :userName and date_of_birth__c=:Dateofbirth.Date_of_Birth__c];
        system.debug('dddddddddddddddddd'+conls );
        if(conls.size() == 1 ) {
            return new pageReference('/apex/studentpersonaldetails');
        }
        else {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please Enter correct User Name or Date of Birth'));

        userName = null;
        Dateofbirth = null;
            return null;
        
        }
        
    }

}

VF :-

<apex:page controller="LoginCntrl" showHeader="false" sidebar="false">
    <apex:form >
        <apex:image id="theImage" value="{!$Resource.nmims2}" width="350" height="60"/><br/>

    <apex:pageBlock title="Login Page" >
    <apex:pageMessages ></apex:pageMessages>

    <br/>

      User Name :  <apex:inputtext value="{!userName}"/> <br/>
       <br/>Date of birth: <apex:inputfield value="{!Dateofbirth.Date_of_Birth__c}"/><br/>
       <br/>
    
        <apex:commandButton style="margin-left:10px" value="Login" action="{!doLogin}"/>
</apex:pageBlock>
    </apex:form>
</apex:page>

 
If we select a particular picklist value  for a field status_of_candidate ='Selected'  in "Interviewing candidates" object then the record should be automatically created in another object which is "selected candidates" using name,email and phone values. These both objects are not related to each other through look up or Master detail. Please find the below code.

trigger ifselectedcreaterecordonsc on Interviewing_Candidates__c (before insert, before update) {

list<Interviewing_Candidates__c > Sel = [select id,name, Candidate_Email__c,Status_Of_Candidate__c,c.Candidate_Phone__c from Interviewing_Candidates__c ];

list<selected_candidates__C> lst = new list<selected_candidates__C>();

for(Interviewing_Candidates__c c : sel){

if(c.Status_Of_Candidate__c == 'Selected'){

selected_candidates__C ss = new selected_candidates__C();

ss.name = c.name;
ss.Email__c =c.Candidate_Email__c;
ss.phone__C =c.Candidate_Phone__c;
 insert c;

}

}

}

Need your help
Hi Everyone,

Can anyone in this forum please help me in understanding why to create visual force pages even for the record creation.I mean when we add object as a tab in an app,salesforce automatically gives us the option for creation,edition and deletion of records.Then what's the need of visualforce in creating,editing and deleting records.And also when we actually go for visualforce?As I am new to salesforce, appreciate your prompt response in understanding this.

Thanks in advance!!
I am trying to delete a cases that were created during testing in Production, we have setup rollup helper on Cases, and Realtime rollups enabled. Deleting a test case results in the following error:

There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Apex trigger RHX_Case caused an unexpected exception, contact your administrator: RHX_Case: execution of BeforeDelete caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.RHX_Case: line 3, column 1"

Changing the rollup helper setting doesn't appear to work either, when I deactivate them. How do I deactivate the rollup helper trigger?
User-added image
I noticed several codes here but none of them are used today by the google code api
trigger populate on project__c (before insert , before update){
 
    
    
     MAP<ID , user> mapCon = new MAP<ID , user>([Select id ,name,city
                                                 from user 
]);
     for(project__c  obj : trigger.new)
       {
        if(obj.delivery_location__c == null)
          {
           user u  = mapcon.get(obj.ownerid);
              if (u.city != null)
              
             obj.Delivery_location__c=u.city;
              else {
                   obj.Delivery_location__c = 'NA';
              }
          }
       
       }
       
       }
1.I have created a custom button which should be accessed by only 1 profile
2.I want restrict access to standard button "new case" button on list view to same profile

Could you please advice how to achieve this?
Trail Head: Build a Conference Management App >Create Apex Triggers

Working on Trigger That Sends Confirmation Emails
If i want to opt Process builder instead of trigger for this particular use case.
Please help me
public class sendofferlettercontroller {

   public sendofferlettercontroller() { }

    public String toEmail {get;set;}
        public String ccEmail {get;set;}
    Public ID ParentID{get;set;}

    public String subject {get;set;}
    public String body {get;set;}
        
    private final contact MyLead;
       public static contact co1{get;set;}

    
    public sendofferlettercontroller(ApexPages.StandardController controller)
    {
        this.MyLead=(Contact)controller.getRecord();
             ParentID = apexpages.currentpage().getparameters().get('id');

    } 
   
             
    public PageReference sendEmail() {
        
           co1 = [select id ,name, Email  from contact where id =: ApexPages.currentPage().getParameters().get('id')];

        //create a mail object to send email 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        String[] toaddress = toEmail.Split(','); //using comma separator between emails
        //String[] toaddress = toEmail.Split('[,;]'); //use can use Regex to mix with comma & semi colon separator

        //email properties
        String[] ccaddress = ccEmail.Split(',');
        mail.setToAddresses(toaddress);
        mail.setSubject(subject);
                           mail.setccAddresses(ccaddress);  

        mail.setUseSignature(true);
        mail.setPlainTextBody(body); 
                
        // send the email'
                             PageReference pdf =  Page.offerletterpage;
                                                  pdf.getParameters().put('id',(String)co1.id);
                     pdf.setRedirect(true);
                                          blob b;

                     try{
                     b = pdf.getContent();
                     }catch (VisualforceException e){
                     b = Blob.valueOf('Some Text');
                     }
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
                     efa.setFileName('ImpactGuru Offer Letter PDf'+'.pdf');
                     efa.setBody(b);
                     mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
                       try
                    {
                 //   Messaging.SendEmailResult[] resultMail = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                    catch(System.EmailException ex)
                    {
                    }
                    Datetime myDatetime = Datetime.now();
                    String myDatetimeStr;  
                    Attachment a = new Attachment();
                    a.parentid = co1.id;
                    a.body = b;
                    a.name = (co1.Name+' - '+myDatetime.format('d - MMMM, yyyy'));
                    insert a;

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        Return Page.sendofferletter;

     }   
   

}

Thanks in advance
Hello friends, I want to add Multiple email address for sending the email in To: input box, but it doesnot accept more than one. Do anyone know how to solve this.
Please find the code below

public class sendemailtestcontroller {

    public sendemailtestcontroller() {

    }





    public String toEmail {get;set;}
    public String subject {get;set;}
    public String body {get;set;}
    
    
    private final Lead MyLead;
    public sendemailtestcontroller(ApexPages.StandardController controller)
    
   
    {
        this.MyLead=(Lead)controller.getRecord();
    } 
   
             
    public void sendEmail() {
        
        //create a mail object to send email 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        
        String[] toaddress = (new String[]{toEmail});
        
        //email properties
        mail.setToAddresses(toaddress);
        mail.setSubject(subject);
        mail.setUseSignature(true);
        mail.setPlainTextBody(body); 
               
        // send the email
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }   
   

}

Vf :
<apex:page standardcontroller="Lead" extensions="sendemailtestcontroller">
  <apex:pageBlock title="EMAIL TEST">
        <apex:form >
        <br />
            <apex:outputLabel value="To" for="To"/>:<br/>
            <apex:inputText value="{!toEmail}" id="email"/><br/><br/>
                        
            <apex:outputLabel value="Subject" for="Subject"/>:<br />     
            <apex:inputTextarea value="{!subject}" id="Subject" cols="80" /><br/><br/>
                        
            <apex:outputLabel value="Body" for="Body"/>:<br />     
            <apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/><br/><br/>      
            <br /><br />
                        
            <apex:commandButton value="Send Email" action="{!sendEmail}"  />
            <apex:commandButton value="Cancel" action="{!cancel}"/> 
        
        </apex:form>
    </apex:pageBlock>
</apex:page>

User-added image
Hi All,

I have a custom VF page for Tasks. Currently, I cannot figure out how to auto populate a custom field, called Account Name, with the actual account name the task is associated with, from the Opportunity. Does anyone know a trigger for this?

Thank you!

Posting this in order to help others who, months from now, might Google "OP_WITH_INVALID_USER_TYPE_EXCEPTION" and find this explanation.

 

We wrote an Apex trigger on the User object, to insert a custom object record anytime a user updates their Chatter status.  This was done to fulfill a client's requirement to audit all Chatter activity.

 

The trigger worked fine, until one day the client signed up some Chatter Free users.  When such a user tried to update their status, they got a pop-up with an OP_WITH_INVALID_USER_TYPE_EXCEPTION error.

 

We scratched our collective heads for awhile.  After all, Apex triggers run in "system mode," right?  That is supposed to mean that "object and field-level permissions of the current user are ignored."  And yet this trigger seemed like it was running in "user mode," enforcing restrictions based on who the current user was.

 

The root cause turned out to be that a Chatter Free user cannot be the owner of a custom object record, and SFDC by default sets the current user as a new record's first owner.  We discovered this when we realized, via experiment, that Apex triggers fired as the result of actions by Chatter Free users could definitely update an existing record, but were having problems creating records.

 

So the simple solution was to explicitly set the owner of the new record to some fully-licensed user prior to inserting it.