• PRO
  • 2385 Points
  • Member since 

  • Chatter
    Feed
  • 82
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 329
    Replies
hello everyone,

Need to add a Custom button on Lead List Page?

 Controller Class :
 
/*
Developer : Azar khasim 
Created Date : 03 MAR 2020
Description : Global Duplicate Search. 
*/

public class GlobalDupSearch1 {
 // PE is for searching for duplicates//   
    public string PE{get;set;}
    public string a;
    
 // These booleans are for capturing the filtered records//
    public boolean cn1{get;set;}
    public boolean ac1{get;set;}
    public boolean ld1{get;set;}
    public boolean ld2{get;set;}
    public boolean opp1{get;set;}
    
 // For Capturing of lead status.   
    public boolean Editlead{get;set;}
    public boolean Createlead{get;set;}
    
 // These lists are to capture the filtered records and stored in the list//
    public list<Account> aclist{get;set;}
    public list<contact> cnlist{get;set;}
    public list<lead> ldlist{get;set;}
    public list<lead> ldlist1{get;set;}
    public list<opportunity> opplist{get;set;}
    
    
    public GlobalDupSearch1(apexpages.StandardController sc){
      a=apexpages.currentPage().getparameters().get('id');  
     //   PE= 'search here...'; 
     
    }
    
    public void search(){
        if(pe != null && pe != ''){
            
            aclist=[select id, name, PersonMobilePhone, PersonEmail, Phone, Owner.name, Owner.UserRoleId, Owner.MobilePhone, Owner.Email, OwnerId from account where PersonMobilePhone like :PE or PersonEmail like :PE]; 
            if(aclist.size() > 0){
                ac1=true;
             }
            else{ 
                ac1=false;
            }
            opplist=[SELECT name, Mobile__c, Email__c, StageName, Owner.name, Owner.UserRoleId, Owner.MobilePhone, Owner.Email, OwnerId from opportunity where Email__c like :PE or Mobile__c like :PE];
            if(opplist.size()>0){
                opp1=true;
             }
            else{
                opp1=false;
            }
            cnlist=[SELECT name, MobilePhone, Email, Owner.name, Owner.UserRoleId, Owner.MobilePhone, Owner.Email, OwnerId from contact where MobilePhone like :pe or Email like :PE]; 
            if(cnlist.size() > 0){
                cn1=true;
             }
            else{
                cn1=false;
            }
            ldlist=[SELECT id,name, MobilePhone, Email, Status, User_Mobile__c, Lead_Owner_Role__c, DUP_Mobile__c, Owner.name, Owner.UserRoleId, Owner.Email, OwnerId, DUP_Update_Owner__c from lead where (Status!= 'Converted' AND Status!= 'Prospect' ) AND (MobilePhone like : pe or Email like :pe or DUP_Mobile__c like : pe)];
            if(ldlist.size() > 0){
                ld1=true;
            }
            else{
                ld1=false;
            }            
            
            ldlist1=[SELECT id,name, MobilePhone, Email, Status, User_Mobile__c, Lead_Owner_Role__c, DUP_Mobile__c, Owner.name, Owner.UserRoleId, Owner.Email, OwnerId, DUP_Update_Owner__c from lead where (Status!= 'New' AND Status!= 'Assigned' AND Status!= 'Followup' AND Status!= 'Junk' ) AND (MobilePhone like : pe or Email like :pe or DUP_Mobile__c like : pe)];
            if(ldlist1.size() > 0){
                ld2=true;
            }
            else{
                ld2=false;
            }          
            
            if(ac1 == false && cn1 == false && ld1 == false && ld2 == false && opp1 == false){
             // To show create lead Button.
                Createlead=true;
                Editlead=false;
                apexpages.Message m=new apexpages.message(ApexPages.Severity.ERROR,'No records found!');
                apexpages.addMessage(m);
            }else{
                Createlead=false;
            }
            
        }else{
            
            Createlead=false;
            Editlead=false;
            apexpages.Message m1=new apexpages.message(ApexPages.Severity.ERROR,'Please enter a Mobile number or Email ID to search duplicates');
            apexpages.addMessage(m1);
            
        }
        
  /// This if action is to hide the Save Button when below creteria meets ///    
  
        if(ld1 == true){
        Editlead=true;
    }  
        
    /*    for(lead lds:ldlist){
             if((lds.Status!= 'converted' || lds.Status!= 'prospect')&&(lds.Lead_Owner_Role__c!= 'Internal Sales Agent' || lds.Lead_Owner_Role__c!= 'Internal Sales Team Lead' || lds.Lead_Owner_Role__c!= 'Internal Sales Team Director')){
                Editlead=true;
                 
             }
        }  */
       
        
    }
    
    public pagereference save(){
        
        //// Need to update OwnerId field of particular record in lead object////
  		list<lead> updateLead = new list<lead>();
        lead ldown = new lead();
        integer NoOfCheckes = 0;
        for(lead ld:ldlist){
            if(ld.DUP_Update_Owner__c == true){
               NoOfCheckes++;
               UpdateLead.add(ld);
            }
        }
        if(UpdateLead.size()==1&& Noofcheckes == 1){
        	    UpdateLead[0].DUP_Update_Owner__c = false;
            	Update UpdateLead[0];
        }else{
            apexpages.Message m2=new apexpages.message(ApexPages.Severity.ERROR,'Please Select one Lead at a time only');
            apexpages.addMessage(m2);
        }
        
        pagereference p1=new pagereference('/'+(UpdateLead.size()>0?UpdateLead[0].id:null));
        p1.setRedirect(true);
        return p1;
        
    }
    
    
    public pagereference createLead(){
       
        pagereference cl1=new pagereference('/lightning/o/Lead/new');
        cl1.setRedirect(true);
        return cl1;
    }
    
}

Visualforce :
 
<!--
Developer : Azar khasim 
Created Date : 03 MAR 2020
Description : Global Duplicate Search. 
-->

<apex:page StandardController="Lead" extensions="GlobalDupSearch1">
    
    <apex:form >
        <apex:pageBlock id="block">
            <apex:pageMessages ></apex:pageMessages>
            <style>
                .custom1 .pbSubheader {
                background-color: #2E9AFE !important;
                }
            </style> 
            
            <center>
                <apex:pageBlockButtons location="bottom" > 
                    <apex:commandButton style="color:black;background-image:none;width:50px;height:30px"  action="{!save}" value="Save" rendered="{!Editlead=true}"/>
                </apex:pageBlockButtons>
            </center> 
            
            
            <!---------- Duplicate Search ---------------------------------------------------------------->            
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Find Dulicates" collapsible="false" >               
                    <center>
                        <apex:inputText value="{!pe}" id="search" html-placeholder="Search here"/><br/>
                        <apex:commandButton value="Search" action="{!search}" rerender="block"/>
                    </center>             
                    <center>
                        <apex:commandButton style="width:75px;height:25px"  action="{!createLead}" value="Create Lead" rendered="{!Createlead=true}"/>
                    </center>
                </apex:pageBlockSection>
            </apex:outputPanel>
            
            
            <!------------------------------------------------------------ Lead Data(No Converted and Prospect Data)  to Display ------------------------------------------------------------------------>   
       
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Lead" rendered="{!ld1 != false}" >
                    
                    <!-- Regarding the Boolean Value in Lead Object ---------------------------------------->       
                    <apex:pageBlockTable value="{!ldlist}" var="Leaddata" cellspacing="10">
                        
                        <apex:column style="width:100px" value="{!Leaddata.Name}" headerValue="Lead Name"/>
                        <apex:column style="width:100px" value="{!Leaddata.Status}" headerValue="Lead Status"/>
                        <apex:column style="width:100px" value="{!Leaddata.Owner.Name}" headerValue="Owner Name"/>
                        <apex:column style="width:100px" value="{!Leaddata.Lead_Owner_Role__c}" headerValue="Owner Role"/>
                        <apex:column style="width:100px" value="{!Leaddata.User_Mobile__c}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!Leaddata.Owner.Email}" headerValue="Owner Email"/>
                        <!----- OwnerId Field in Lead Object ----------------------------------------------->      
                       
                        <apex:column >
                            <apex:facet name="header">New Lead Owner</apex:facet>
                              <apex:inputField value="{!Leaddata.ownerId}" required="false" rendered="{!IF((Leaddata.Lead_Owner_Role__c ='Internal Sales Agent'||Leaddata.Lead_Owner_Role__c ='Internal Sales Team Lead'||Leaddata.Lead_Owner_Role__c ='Internal Sales Team Director'),false,true)}"/>
                        </apex:column> 
                        <apex:column headerValue="Change Ownership" >
                            <apex:inputCheckbox value="{!Leaddata.DUP_Update_Owner__c}"  label="Change Ownership" rendered="{!If((Leaddata.Lead_Owner_Role__c ='Internal Sales Agent'||Leaddata.Lead_Owner_Role__c ='Internal Sales Team Lead'||Leaddata.Lead_Owner_Role__c ='Internal Sales Team Director'),false,true)}"/> 
                        </apex:column> 
                        
                    </apex:pageBlockTable>
                    
                </apex:pageBlockSection>
            
            </apex:outputPanel> 
          
            
            <!------------------------------------------------------------ Lead 2 Data(No New, Assigned, Followup and Junk Data)  to Display ------------------------------------------------------------------------>   
       
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="SalesOwner leads" rendered="{!ld2 != false}" >
                    
                    <!-- Regarding the Boolean Value in Lead Object ---------------------------------------->       
                    <apex:pageBlockTable value="{!ldlist1}" var="lds" cellspacing="10">
                        
                        <apex:column style="width:100px" value="{!lds.Name}" headerValue="Lead Name"/>
                        <apex:column style="width:100px" value="{!lds.Status}" headerValue="Lead Status"/>
                        <apex:column style="width:100px" value="{!lds.Owner.Name}" headerValue="Owner Name"/>
                        <apex:column style="width:100px" value="{!lds.Lead_Owner_Role__c}" headerValue="Owner Role"/>
                        <apex:column style="width:100px" value="{!lds.User_Mobile__c}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!lds.Owner.Email}" headerValue="Owner Email"/>
                        <!----- OwnerId Field in Lead Object ----------------------------------------------->      
                       
                    </apex:pageBlockTable>
                    
                </apex:pageBlockSection>
            
            </apex:outputPanel> 
          
            <!------------------------------------------------------- Opportunity Data  to Display ---------------------------------------------------------------------------->             
       
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Opportunity" rendered="{!opp1 != false}">
                    
                    <!--- Values to display in Opportunity Object---------------------------------------->
                    <apex:pageBlockTable style="width:150%" value="{!opplist}" var="opp"  cellspacing="10">

                        <apex:column style="width:100px" value="{!opp.name}" />  
                        <apex:column style="width:100px" value="{!opp.StageName}" headerValue="Opportunity Stage"/>
                        <apex:column style="width:100px" value="{!opp.owner.Name}" headerValue="Owner"/>  
                        <apex:column style="width:100px" value="{!opp.owner.UserRoleId}" headerValue="Owner Role"/>
                        <apex:column style="width:100px" value="{!opp.owner.MobilePhone}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!opp.owner.Email}" headerValue="Owner Email"/>   
                        <!----- OwnerId Field in Lead Object ----------------------------------------------->      
                        
                    </apex:pageBlockTable>
                </apex:pageBlockSection>
            </apex:outputPanel>

            <!---------------------------------------------------------- Account Data  to Display ---------------------------------------------------------------------->             
    <!--     
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Account" rendered="{!ac1 != false}">  -->
 
                    <!--- Values to display in Account Object---------------------------------------->
               <!--     <apex:pageBlockTable style="width:150%" value="{!aclist}" var="ac"  cellspacing="10">
 
                        <apex:column style="width:100px" value="{!ac.Name}" />  
                        <apex:column style="width:100px" value="{!ac.owner.Name}" headerValue="Owner"/>
                        <apex:column style="width:100px" value="{!ac.owner.UserRoleId}" headerValue="Owner Role" />
                        <apex:column style="width:100px" value="{!ac.owner.MobilePhone}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!ac.owner.Email}" headerValue="Owner Email"/>   
                        
                         
                    </apex:pageBlockTable>
                </apex:pageBlockSection>
            </apex:outputPanel>  -->
            
            <!------------------------------------------------------------- Contact Data  to Display --------------------------------------------------------------------->             
         
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Account / Contact" rendered="{!cn1 != false}">

                    <!---  Values to display in Contact Object-------------------------------------------->
                    <apex:pageBlockTable style="width:150%" value="{!cnlist}" var="con"  cellspacing="10">

                        
                        <apex:column style="width:100px" value="{!con.Name}" />  
                        <apex:column style="width:100px" value="{!con.owner.Name}" headerValue="Owner"/>  
                        <apex:column style="width:100px" value="{!con.owner.UserRoleId}" headerValue="Owner Role"/>
                        <apex:column style="width:100px" value="{!con.owner.MobilePhone}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!con.owner.Email}" headerValue="Owner Email"/> 
                        
                         
                    </apex:pageBlockTable>
                </apex:pageBlockSection>
            </apex:outputPanel> 
            
            <!-------- End of logics ------------------------------------------------------------------------------->     
        </apex:pageBlock>
    </apex:form>
</apex:page>

Now i need to create a List Button On Lead List Page.
to access this Vf page.

Please provide me a solution.

Thanks and Regards,
Azar Khasim.
Hi,

I try to upload an apex class from the sandbox to the prod. and receiving following error:

System.NullPointerException: Attempt to de-reference a null object
Stack Trace: Class.ClsApplicationTrainingRequestController.getPickValues: line 57, column 1 Class.ClsAppTrainRequestController_Test.myUnitTest: line 52, column 1

The person who has created the custom code has left the company years ago and I have no apex skills. Can anyone please help me with this?

Apex Class
public class ClsApplicationTrainingRequestController {

    public Application_Training_Request__c appRequest {get;set;}
    public Id trainRecordType;
    
    public ClsApplicationTrainingRequestController(ApexPages.StandardController stdController){
        Id oppyId = System.currentPageReference().getParameters().get('oppyId');
        Opportunity oppy = [Select OwnerId,AccountId,Market_sub_Segment__c,Market_Segment__c,Id,Business_Unit__c,BNG_Strategic_Market__c 
                        From Opportunity where id=:oppyId];
        appRequest = new Application_Training_Request__c();
        if(oppyId != null){
            appRequest.opportunity_name__c = oppyId;
            //appRequest.market_segment__c = oppy.market_segment__c;
            //appRequest.market_subsegment__c = oppy.market_sub_segment__c;
            appRequest.business_unit__c = oppy.business_unit__c;
            appRequest.opportunity_owner__c = oppy.ownerid;
            //appRequest.bng_strategic_market__c = oppy.bng_strategic_market__c;
            appRequest.account_name__c = oppy.accountid;    
            
            List<OpportunityCompetitor> oppyCompetitorList = [SELECT OpportunityId, Id, CompetitorName FROM OpportunityCompetitor 
                        where OpportunityId =:oppyId];
            String competitors = '';
            Map<String,String> resutlMap = new Map<String,String>();
            System.debug('---oppyCompetitorList');
            for(OpportunityCompetitor oppyComp : oppyCompetitorList){
                System.debug(resutlMap + '---resutlMap' + oppyComp.competitorname);
                if(!resutlMap.containsKey(oppyComp.competitorname)){
                    if(competitors != ''){
                        competitors += ';'; 
                    }
                    competitors += oppyComp.competitorname; 
                    resutlMap.put(oppyComp.competitorname,oppyComp.competitorname);
                    System.debug(competitors + '----' + oppyComp.competitorname);
                }
            }
            appRequest.competitor__c = competitors;
        }
    }
    
    public List<RecordType> getRecordTypeList(){
        List<RecordType> recordList = [Select Name,Id,Description,developername From RecordType where SobjectType='Application_Training_Request__c'];
        for(RecordType rt : recordList){
            if('Training_Request'.equals(rt.developername)){
                trainRecordType = rt.id;    
            }
        }
        return recordList;
    }
    public List<selectOption> getPickValues(Sobject object_name, String field_name, String first_val) {
        List<selectOption> options = new List<selectOption>(); //new list for holding all of the picklist options
        if (first_val != null) { //if there is a first value being provided
           options.add(new selectOption(first_val, first_val)); //add the first option
        }
        Schema.sObjectType sobject_type = object_name.getSObjectType(); //grab the sobject that was passed
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
        List<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject
        for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
                      
             options.add(new selectOption(a.getValue(), a.getLabel())); //add the value and label to our final list
        }
        System.debug('--options' + options);
        return options; //return the List
        
    }

    public PageReference saveRequest(){
        try{
            system.debug('www saveRequet appRequest : ' + appRequest);
            if(appRequest.recordtypeid != trainRecordType){
                //appRequest.request_type__c = 'Sample Analysis';
                //appRequest.permission_on_sample_preparation__c = 'permitted';
                //appRequest.sample_status_indicator__c = 'received';
            }
            insert appRequest;
            System.debug('--appRequest---' + appRequest);
            PageReference requestPage = new ApexPages.StandardController(appRequest).view();
            requestPage.setRedirect(true);
            return requestPage;
        }catch(Exception ex){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ex.getStackTraceString()));
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            System.debug('Method---:saveRequest-- linenumber :' + ex.getLineNumber() + '---message:' + ex.getMessage());
            return null;
        }
    }
}



Test Class
/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class ClsAppTrainRequestController_Test {

    /*static testMethod void myUnitTest() {
        Account acc = new Account();
        acc.Name = 'jinbo test accoutn13';
        insert acc;
        
        Opportunity oppy = new Opportunity();
        oppy.AccountId = acc.Id;
        oppy.StageName = 'Closed Lost';
        oppy.Name = 'test oppy name';
        oppy.CloseDate = system.today();
        insert oppy;
        OpportunityCompetitor oppyComp = new OpportunityCompetitor();
        oppyComp.competitorname = 'Atominstitut Wien';
        oppyComp.opportunityid = oppy.id;
        insert oppyComp;
        
        OpportunityCompetitor oppyComp2 = new OpportunityCompetitor();
        oppyComp2.competitorname = 'Bowman';
        oppyComp2.opportunityid = oppy.id;
        insert oppyComp2;
        
        List<RecordType> recordList = [Select Name,Id,Description,developername From RecordType where SobjectType='Application_Training_Request__c' and developername='Application_Request'];
        System.currentPageReference().getParameters().put('oppyId',oppy.id);
        ApexPages.StandardController extController = new ApexPages.StandardController(new Application_Training_Request__c());
        ClsApplicationTrainingRequestController contr = new ClsApplicationTrainingRequestController(extController);
        contr.getRecordTypeList();
        contr.saveRequest();
        contr.getPickValues(new Application_Training_Request__c(),'request_type__c',null);
        if(recordList != null && !recordList.isEmpty())
            contr.appRequest.recordtypeid = recordList.get(0).id;
    }*/
}

Thanks in advance!


 
So I'm new to writing apex triggers and need to push a few into production. My trigger code is: 
 
trigger Days_Open on Contact (after insert,after update) {
    List<account> li=new list<Account>();
    List<Id> ids = new List<Id>();
    for(Contact c: trigger.new)
        ids.add(c.AccountId);
    Map<Id, Account> accountMap = new Map<Id, Account>([Select Id, Phone From Account Where Id In :ids]);
    for(Contact c: trigger.new)
    {
        Account a = accountMap.get(c.AccountId);
        if(a != null)
        {
            a.Days_Open__c = c.Days_Open__c;
            li.add(a);
        }
    }
    update li;
}
How do I write a test class? Trigger works in the environment. I need to have it check that when a contact record is saved it copies it to the account that the contact is related too. I currently cannot push into production as code coverage is at 0%
 
I need to expose a visualforce page on a custom object( Support Request) when SLA is breached for that support Request.
When Today date>= SLA Due Details, visualforce component on the Support Request page should show below message
"SLA Breached, please treat this on priority"

I have created below VF page and trying to expose on the page layout:

<apex:page standardController="Support_Request__c"> if (SLA_Details__c == null) { ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'SLA Breached')); return null; } </apex:page>

But its not working fine, Kindly suggest

trigger DateofBirth on Account (before insert) {
    for(Account a:trigger.new){
        if(a.Date_of_Birth__c!=NUll && ((system.today()- a.Date_of_Birth__c)/365 <=18)){
            a.Date_of_Birth__c.adderror('Age should be more than 18');
        }
    }
}

 

error i am facing:

Date expressions must use Integer or Long

 Suppose there is a profile P1 and it has users U1, U2 and U3. There is  a custom object CO1 and has fields F1, F2, F3,... F10. Now I want to give access to U1 to fields from F1 to F5 and other users U2 and U3 to fileds F6 to F10. How do i do that??
Hi Megha , 
 
What is SALES CLOUD LIFE CYCLE? with simple Example I want to know basic concept related salescloud object

 
 
Thanks in Advance.
Hi members, need help !

I am trying to create a Trigger (on Lead object) for Email Alert based on the Username. In the sense-  whenever a user deletes a lead record, an email should go out the the manager.... but getting across the below error. 
Can someone please rectify my Trigger and suggest that wrong am i doing here ?

*** TRIGGER***

trigger EmailAfterDeleteLead on Lead(after delete) {
    Messaging.reserveSingleEmailCapacity(trigger.size);
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
            for (Lead lead : Trigger.old) { 
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                    if (userInfo.LastName=='Event Catering' && userInfo.LastName=='General Catering'){
                        email.setToAddresses(new String[] {'Manager@Functions.com'});
                        }
                        Else {
                    email.setToAddresses(new String[] {'Administrator@Functions.com'});
                email.setSubject('Deleted Lead Alert');
            email.setPlainTextBody('Dear Manager,' +'\n'+ 'This message is an alert that the following lead has been deleted from Salesforce by *** ' + UserInfo.getFirstName() + ' ' + UserInfo.getLastName() + '***. You can restore the deleted lead from recycle bin within 15 days ' + '\n \n'
        + 'Lead Name: ' + lead.FirstName + ' ' + lead.LastName + '\n'
        + 'Lead Email: ' + lead.Email + '\n'
        + 'Lead Status: ' + lead.Status + '\n'       
        + 'Lead Id: ' + lead.Id + '\n\n'
        + 'Current Salesforce User Name: ' + UserInfo.getFirstName() + ' ' + UserInfo.getLastName() +  '\n\n\n\n\n'
        );
        emails.add(email);
        }
        
    }
    Messaging.sendEmail(emails);

}

============================

User-added image
Hi Salesforce Experts,

Could you please tell me how to write a program to check if two strings are anagram of each other in Apex?

Thanks in Advance.
<apex:page controller="ContactsVisualforceController" standardStylesheets="false"> <apex:pageBlock> <apex:repeat value="{!displayAccounts}" var="acc"> <dl> <dt>Account Name:</dt> <dd><apex:outputText value="{!acc.Name}"/></dd> </dl> <dl><dt>Contacts:</dt></dl> <apex:repeat value="{!acc.Contacts}" var="cont"> <dl> <dd><apex:outputText value="{!cont.Name}"/></dd> </dl> </apex:repeat> </apex:repeat> </apex:pageBlock> </apex:page>

Hi, i try to test my wrapper class but i have actually 0% coverage.

My wrapper is like :

public class EU01AccountApiWrapper {

    public String code;
    public String name;
    public cls_status status;
    public String website;

...
In my test method i have try to create a wrapper 
EU01AccountApiWrapper wrapper= new EU01AccountApiWrapper();
    wrapper.code = 'Test Wrapper';
    wrapper.name = 'Test Wrapper';


But i have 0%. How can i do ? Ty :)

Hi,

I have the following trigger.

When a child record (Opportunity Product Lines) on the opportunity gets updated, it queries all child records of the same type on the opportunity and stamps a sum of one of the fields up to the opportunity.

I understand that because of the structure of the trigger I cannpot just write a simple, create product lines trigger so this one is proving a little difficult for me. 

Is there anyone that would be able to help me write a test class for the below trigger. I am now to APEX.

trigger RollUpIncpasulaCountOnOpp on Opportunity_Product_Line__c (after insert){
List<Opportunity> OppList = new List<Opportunity>();
   
   Set<Id> OppIds = new Set<Id>();

     for(Opportunity_Product_Line__c OpptoUpdate:Trigger.New) {
      
        OppIds.add(OpptoUpdate.Opportunity__c);   

     }
   
    
    AggregateResult[] groupedResults = [SELECT Opportunity__c, sum(Requires_Incapsula_ID__c) IncapProducts FROM Opportunity_Product_Line__c where Opportunity__c IN :OppIds GROUP BY Opportunity__c ];

    for(AggregateResult ar:groupedResults) {
        
        Id Oppid = (ID)ar.get('Opportunity__c');
        Opportunity Opp1 = new Opportunity(Id=Oppid);   
        Opp1.Count_Incapsula_Products__c = (double.valueOf(ar.get('IncapProducts')));  
        OppList.add(Opp1);

   }      
      
   update OppList;

    
Our Salesforce team are planning to use a code repository to commit all code changes.
However, the question we are currently asking ourselves is what metatdata should be committed to the repository.
We definately want all Apex code and triggers under version control.
We are thinking that profiles and permission sets should be excluded from version control.
However what about standard and custom objects, which of course include validation rules, sharing etc?
And what about workflow rules, process flows etc, they contain logical processing so should they be under version control?

Lots to think about, if anyone has been through this and has any advice on what worked well for them that would be great.

Many thanks
  • February 21, 2020
  • Like
  • 0
I have a class on which i need to call 'createUserAccount' method but how to set parameter for this method in anonymous window , I do not know please help on this
/**
* @author: Shubham Sinha
* @date: 02/10/2020
* @description: This class is used for creating User Account and User records when a person tries to Login through Janrain
**/

Public Class BIIB_CreateAccountAndUser_Helper{
    /**
* 
* @description: Wrapper class for User and Account Creation, getting wrapper values from BIIB_ADU_Janrain_AuthProviderHandler Class

**/    
    Public class registrationDetails {
        
        public String firstName;
        public String lastName;
        public String fullName;
        public String email;
        public String username;
        public String locale;
        public String provider;
        Public String siteLoginUrl; 
        Public String identifier; 
        Public String link;
        Public Map<String,String> attributeMap;
        
       
    }
    
    /**
* @author: Shubham Sinha
* @description: Creates User Account and Patient therapy record.

**/
    public Static User createUserAccount(registrationDetails regDetailsWrapObj){
        Product_vod__c prodCatlog = [SELECT Name FROM Product_vod__c WHERE Name = :System.label.BIIB_Product_Aducanumab];
        Id recordTypeId = Schema.SObjectType.BIIB_Patient_Therapy__c.getRecordTypeInfosByName().get('BIIB_AD').getRecordTypeId();
        Id recordTypeIdAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('BIIB_Patient').getRecordTypeId();
        
        List<Account> checkAccountData = [SELECT id,FirstName, LastName, PersonEmail,BIIB_PASS_Zip_Code__c FROM Account 
                                          WHERE LastName =: regDetailsWrapObj.LastName AND BIIB_PASS_Zip_Code__c =: regDetailsWrapObj.attributemap.get('ZIP')
                                          AND PersonEmail =: regDetailsWrapObj.Email Limit 1 ];
        Account createAccount;
        if(checkAccountData.size()> 0)
        {
            createAccount = checkAccountData[0];
            BIIB_Patient_Therapy__c patTherapy = new BIIB_Patient_Therapy__c();
            patTherapy.RecordTypeId = recordTypeId;
            patTherapy.BIIB_Indication__c = System.label.BIIB_Patient_Therapy_Indication;
            patTherapy.BIIB_Therapy__c = prodCatlog.Name;
            patTherapy.BIIB_Patient__c= createAccount.id;
            
            insert patTherapy;
        }
        else 
        {
           
            createAccount = new Account ();
            createAccount.FirstName= regDetailsWrapObj.firstName;
            createAccount.LastName =regDetailsWrapObj.lastName;
            createAccount.RecordTypeId = recordTypeIdAccount;
            insert createAccount;
 
          BIIB_Patient_Therapy__c accPatTherapy = new BIIB_Patient_Therapy__c();
            accPatTherapy.BIIB_Indication__c = System.label.BIIB_Patient_Therapy_Indication;
            accPatTherapy.BIIB_Therapy__c = prodCatlog.Name;
            accPatTherapy.BIIB_Patient__c= createAccount.id;
            insert accPatTherapy;

            
        }
        User aduUser = createAduCommunityUser(regDetailsWrapObj, createAccount.id);
        return aduUser;
    }
    
    public Static User createAduCommunityUser(registrationDetails regDetailsWrapObj, Id accountId){
        //create community user with related account id
        User aduUser = new User();
        aduUser.contactId = accountId;
        return aduUser;
    }
    
}
I have a requirement where CustomerSuccess__c field on opportunity to be updated  'true' if CustomerSuccess__c field on Account is 'true' in before Insert event.

I have tried below solution, trigger saved succesfully but it didn't work.
Can anyone explain why my trigger is not working
trigger OppoCustomerSuccessCheckboxUpdate on Opportunity (before insert) 
{
for(Opportunity opp : Trigger.New)
{
	if(Opp.AccountID != null)
	{
		if(Opp.Account.CustomerSuccess__c)
		{
			Opp.CustomerSuccess__c = true;
		}
	}
}
}
Regards,
Akash
 
I have wrote a test class for an Apex class,but the code coverage is 42%.

Kindly help me where I'm wrong in the code.

Apex Class:
public class InsertContactsToAccount {
    
    
   @AuraEnabled
    public static void saveContacts(List<Contact> listContact, Id recordId)
    {
        list<contact> conlist = new list<contact>();
        Insert listContact;
        for(Contact a:listContact){
            a.AccountId = recordId;
            conlist.add(a);
        }
        update conlist;
    } 
}

Test Class:
 
@isTest
public class InsertContactsToAccountTest {
    static testMethod void saveContactsTest(){
        
        Account a = new Account();
        a.Name ='Test';
        insert a;
        
        Contact c = new Contact();
        c.LastName = 'Test';
        insert c;
        
        c = [select id from Contact where id =:c.id];
        c.AccountId = a.Id;
        update c;
        
        List<Contact> con = [select id from Contact where id =:c.id];
        InsertContactsToAccount.saveContacts(con,a.id);
        
    }

}

Thanks in Advance 

Regards
Surya
I have written the below code to update bulk records to add all opportunity amount on quota object. Since it is a bulk record I have used asynchronous bulk update records.


public with sharing class listopponquota {
     public list<Opportunity> oppList{get;set;}
    public list<quota__c> qutoaList{get;set;}
    public set<ID> oppIds = new set<ID>(); 
 
public void listopponquota()
    {
        String selectedVal ='';
        oppList = new list<Opportunity>();
        qutoaList = new list<quota__c>();
        oppList();
    }
    
    
    
    public pageReference oppList() {
        Id qId = (Id) ApexPages.currentPage().getParameters().get('id');
        system.debug('Id-->'+qId);    
        List<quota__c> quotaList1 = new List<quota__c>();
        List<Opportunity> oppList1 = new List<Opportunity>();
        
        quotaList1 =[select Id, Name,Start_Date__c,End_Date__c,Assign_to_User__c,Actual_Amount__c, OwnerId from quota__c where Id   =: qId Limit 1];
        oppList1 = [Select Id, Name, CloseDate, StageName,OwnerId,Amount From Opportunity where StageName = 'Closed Won'];
        
        system.debug('quotaList1-->'+quotaList1);
        if(quotaList1.size() > 0){
            for(quota__c q : quotaList1){
                
                for(Opportunity opp : oppList1){
                    system.debug('closedDate-->'+opp.CloseDate);
                    if(opp.CloseDate  >=  q.Start_Date__c  && opp.CloseDate <= q.End_Date__c && q.Assign_to_User__c == q.OwnerId){
                        oppList.add(opp);
                        oppIds.add(opp.id);
                    } 
                }                
            }
        }
        for(aggregateresult ag : [SELECT SUM(Amount) sum FROM Opportunity where ID =:oppIds]){
            system.debug('oppList-->'+double.valueof(ag.get('SUM')));
            for(quota__c q : quotaList1){
                if(q.Actual_Amount__c != double.valueof(ag.get('SUM'))){
                    q.Actual_Amount__c = double.valueof(ag.get('SUM'));
                    qutoaList.add(q);
                   
                }
            }
        }
        system.debug('oppList-->'+oppList.size());
        return null;
    }
    
    public class FutureClassLimitsTest {

    @future(callout=true)
    public static void docallouts(){
  
        system.debug('qutoaList-->'+qutoaList.size());
        if(qutoaList.size()>0){
            
            update qutoaList;
        }
        
    }
}
User-added image
I woud like to simply add 15 minutes to a date and time field. How can I do this?
Hi Experts,
  Pls help me to solve the below issue.I am trying to take a trailhead challenge and i have created the below class and it is working fine able to create the account ,but when i am checking the challenge completion i am getting the error.

public class AccountHandler {
      public static Object insertNewAccount(String strNames)
      {
          try
          {
          Account acct = new Account();
            acct.Name = strNames;
            acct.Phone = '(415)555-1212';
            acct.NumberOfEmployees = 100;
        insert acct;
        //ID acctID = acct.Id;
// Display this ID in the debug log
//System.debug('ID = ' + acctID);
              return acct;
          }
          catch(DmlException  ex)
          {
              System.debug('Got the Error:' +ex.getMessage());
              return null;
          }
      }

}

Challenge not yet complete in My Trailhead Playground 1
Executing the 'insertNewAccount' method failed. Either the method does not exist, is not static, or does not insert the proper account.
Hello Everyone, I want to display Date in Date formate but it's showing in Milliseconds. 

i have attached vf code, query, and output on VF page.

How to display Date insted of Milliseconds.

Visualforce code:
<td>
{{#if this.CC_Shipment__r.Date_Shipped__c}}
{{this.CC_Shipment__r.Date_Shipped__c}}
{{else}}
   -
{{/if}}
</td>
Query:
SELECT CC_Shipment__r.Date_Shipped__c FROM CC_Shipment_Line_Items__c
Query Result:
Query result on Developer console

Output on VF page:
Output on VF page.

I want to convert this Milliseconds(1569283200000) and show it in Date formate (2019-09-24).

Thank you🙂
how to use fieldset in lightning component for creation of  form edit and view in the account object
 Right side block should display Account name as a heading and its related contacts under that account make those changes.
 page block 2 is not working ...?

// class

public class AccountSelectClassController {

    public list<wrapaccount> wrapaccountList { get; set; }
    public list<account> selectedAccounts{get;set;}     
    public list<id> selectedrecordsIds{get;set;}
    public list<Contact> records{get;set;}
    public list<Account> names{get;set;}

    public AccountSelectClassController ()
    {
      
       if(wrapaccountList ==null)
            {
                 wrapaccountList =new list<wrapaccount>();
                 for(account a:[select id,name from account limit 10])
                 {
                 wrapaccountlist.add(new wrapaccount(a));
        
                  }
            }
     }
    
     public void ProcessSelected()
     {
       selectedAccounts=new list<account>();
       selectedrecordsIds =new list<id>();
       records =new List<Contact>();
       names =new List<Account>();
       for(wrapaccount wrapobj:wrapaccountlist)
          {
              if(wrapobj.isSelected==true)
                {
                   selectedAccounts.add(wrapobj.accn);
                }   
          }
          
          for(Account abc:selectedAccounts)
          {
            selectedrecordsIds.add(abc.id);   
          }
                names = [SELECT Name,label__c FROM ACCOUNT WHERE Id IN :selectedrecordsIds];
         
             records = [SELECT Name FROM Contact WHERE AccountId IN : selectedrecordsIds];
               
             System.debug('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'+records);

          System.debug('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'+selectedrecordsIds);
            System.debug('ccccccccccccccccccccccccccccccccccccccc'+names);

      }
      
  
   
   public class wrapaccount
   {
    
    public account accn{get;set;}
    public boolean isSelected{get;set;}
     
       public wrapaccount(account a)
       {
     
         accn=a;
         isselected=false;
       }
   }
}


vf pafe :-
<apex:page sidebar="false" controller="AccountSelectClassController">
    
    
    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");
            for(var i=0; i<inputCheckBox.length; i++){
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    
    </script>
 <apex:form >
    
     <apex:pageBlock id="block2">
       
       <apex:pageBlockSection columns="2">
         <apex:pageBlockTable value="{!wrapaccountList}" var="waccl">
            
           <apex:column >
              <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
            <apex:inputCheckbox value="{!waccl.isSelected}" id="InputId"/>
           </apex:column>
            
            <apex:column value="{!waccl.accn.name}"/>
         </apex:pageBlockTable>
           <apex:pageBlock >
           
   
          <apex:pageBlockTable value="{!names}" var="aaa">
             <apex:column value="{!aaa.Name}" headerValue="name"/>

                                
               
              <apex:pageBlockTable value="{!records}" var="qqq">
                  <apex:column value="{!qqq.name}"/>
              </apex:pageBlockTable>
              </apex:pageBlockTable>

           </apex:pageBlock>
       </apex:pageBlockSection>
         
         <apex:pageBlockButtons location="bottom">
          <apex:commandButton action="{!ProcessSelected}" value="Show Selected Contacts" reRender="block2"/>
        </apex:pageBlockButtons>
         
     </apex:pageBlock>
    
   </apex:form>
</apex:page>


 
public inherited sharing class LWCExampleController {
    @AuraEnabled(Cacheable = true)
    public static list<Account> fetchAccounts(String strObjectName) {
        if(String.isNotBlank(strObjectName)) {
            return Database.query('SELECT Id, Name, Industry From ' + strObjectName + ' limit 10');
        }
        else {
            return null;
        }
    }
}
Hey guys, I have a custom object for Product line items. I need to prepopulate the Quantity with value 1 when creating a record.

So far I know it works as a standard function with Opportunity:

https://help.salesforce.com/articleView?id=customize_oppproduct.htm&type=5

But with custom objects I can not find a solution. How?
Here is what my people are asking for - do we have this option? I can't find any documentation on it. 

When on the tasks page, is there an option to have the calendar sit on the page, istead of having to click it open and then pick a date? Trying to reduce our clicks! 

Thanks in advance, new admin :) 
hello everyone,

Need to add a Custom button on Lead List Page?

 Controller Class :
 
/*
Developer : Azar khasim 
Created Date : 03 MAR 2020
Description : Global Duplicate Search. 
*/

public class GlobalDupSearch1 {
 // PE is for searching for duplicates//   
    public string PE{get;set;}
    public string a;
    
 // These booleans are for capturing the filtered records//
    public boolean cn1{get;set;}
    public boolean ac1{get;set;}
    public boolean ld1{get;set;}
    public boolean ld2{get;set;}
    public boolean opp1{get;set;}
    
 // For Capturing of lead status.   
    public boolean Editlead{get;set;}
    public boolean Createlead{get;set;}
    
 // These lists are to capture the filtered records and stored in the list//
    public list<Account> aclist{get;set;}
    public list<contact> cnlist{get;set;}
    public list<lead> ldlist{get;set;}
    public list<lead> ldlist1{get;set;}
    public list<opportunity> opplist{get;set;}
    
    
    public GlobalDupSearch1(apexpages.StandardController sc){
      a=apexpages.currentPage().getparameters().get('id');  
     //   PE= 'search here...'; 
     
    }
    
    public void search(){
        if(pe != null && pe != ''){
            
            aclist=[select id, name, PersonMobilePhone, PersonEmail, Phone, Owner.name, Owner.UserRoleId, Owner.MobilePhone, Owner.Email, OwnerId from account where PersonMobilePhone like :PE or PersonEmail like :PE]; 
            if(aclist.size() > 0){
                ac1=true;
             }
            else{ 
                ac1=false;
            }
            opplist=[SELECT name, Mobile__c, Email__c, StageName, Owner.name, Owner.UserRoleId, Owner.MobilePhone, Owner.Email, OwnerId from opportunity where Email__c like :PE or Mobile__c like :PE];
            if(opplist.size()>0){
                opp1=true;
             }
            else{
                opp1=false;
            }
            cnlist=[SELECT name, MobilePhone, Email, Owner.name, Owner.UserRoleId, Owner.MobilePhone, Owner.Email, OwnerId from contact where MobilePhone like :pe or Email like :PE]; 
            if(cnlist.size() > 0){
                cn1=true;
             }
            else{
                cn1=false;
            }
            ldlist=[SELECT id,name, MobilePhone, Email, Status, User_Mobile__c, Lead_Owner_Role__c, DUP_Mobile__c, Owner.name, Owner.UserRoleId, Owner.Email, OwnerId, DUP_Update_Owner__c from lead where (Status!= 'Converted' AND Status!= 'Prospect' ) AND (MobilePhone like : pe or Email like :pe or DUP_Mobile__c like : pe)];
            if(ldlist.size() > 0){
                ld1=true;
            }
            else{
                ld1=false;
            }            
            
            ldlist1=[SELECT id,name, MobilePhone, Email, Status, User_Mobile__c, Lead_Owner_Role__c, DUP_Mobile__c, Owner.name, Owner.UserRoleId, Owner.Email, OwnerId, DUP_Update_Owner__c from lead where (Status!= 'New' AND Status!= 'Assigned' AND Status!= 'Followup' AND Status!= 'Junk' ) AND (MobilePhone like : pe or Email like :pe or DUP_Mobile__c like : pe)];
            if(ldlist1.size() > 0){
                ld2=true;
            }
            else{
                ld2=false;
            }          
            
            if(ac1 == false && cn1 == false && ld1 == false && ld2 == false && opp1 == false){
             // To show create lead Button.
                Createlead=true;
                Editlead=false;
                apexpages.Message m=new apexpages.message(ApexPages.Severity.ERROR,'No records found!');
                apexpages.addMessage(m);
            }else{
                Createlead=false;
            }
            
        }else{
            
            Createlead=false;
            Editlead=false;
            apexpages.Message m1=new apexpages.message(ApexPages.Severity.ERROR,'Please enter a Mobile number or Email ID to search duplicates');
            apexpages.addMessage(m1);
            
        }
        
  /// This if action is to hide the Save Button when below creteria meets ///    
  
        if(ld1 == true){
        Editlead=true;
    }  
        
    /*    for(lead lds:ldlist){
             if((lds.Status!= 'converted' || lds.Status!= 'prospect')&&(lds.Lead_Owner_Role__c!= 'Internal Sales Agent' || lds.Lead_Owner_Role__c!= 'Internal Sales Team Lead' || lds.Lead_Owner_Role__c!= 'Internal Sales Team Director')){
                Editlead=true;
                 
             }
        }  */
       
        
    }
    
    public pagereference save(){
        
        //// Need to update OwnerId field of particular record in lead object////
  		list<lead> updateLead = new list<lead>();
        lead ldown = new lead();
        integer NoOfCheckes = 0;
        for(lead ld:ldlist){
            if(ld.DUP_Update_Owner__c == true){
               NoOfCheckes++;
               UpdateLead.add(ld);
            }
        }
        if(UpdateLead.size()==1&& Noofcheckes == 1){
        	    UpdateLead[0].DUP_Update_Owner__c = false;
            	Update UpdateLead[0];
        }else{
            apexpages.Message m2=new apexpages.message(ApexPages.Severity.ERROR,'Please Select one Lead at a time only');
            apexpages.addMessage(m2);
        }
        
        pagereference p1=new pagereference('/'+(UpdateLead.size()>0?UpdateLead[0].id:null));
        p1.setRedirect(true);
        return p1;
        
    }
    
    
    public pagereference createLead(){
       
        pagereference cl1=new pagereference('/lightning/o/Lead/new');
        cl1.setRedirect(true);
        return cl1;
    }
    
}

Visualforce :
 
<!--
Developer : Azar khasim 
Created Date : 03 MAR 2020
Description : Global Duplicate Search. 
-->

<apex:page StandardController="Lead" extensions="GlobalDupSearch1">
    
    <apex:form >
        <apex:pageBlock id="block">
            <apex:pageMessages ></apex:pageMessages>
            <style>
                .custom1 .pbSubheader {
                background-color: #2E9AFE !important;
                }
            </style> 
            
            <center>
                <apex:pageBlockButtons location="bottom" > 
                    <apex:commandButton style="color:black;background-image:none;width:50px;height:30px"  action="{!save}" value="Save" rendered="{!Editlead=true}"/>
                </apex:pageBlockButtons>
            </center> 
            
            
            <!---------- Duplicate Search ---------------------------------------------------------------->            
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Find Dulicates" collapsible="false" >               
                    <center>
                        <apex:inputText value="{!pe}" id="search" html-placeholder="Search here"/><br/>
                        <apex:commandButton value="Search" action="{!search}" rerender="block"/>
                    </center>             
                    <center>
                        <apex:commandButton style="width:75px;height:25px"  action="{!createLead}" value="Create Lead" rendered="{!Createlead=true}"/>
                    </center>
                </apex:pageBlockSection>
            </apex:outputPanel>
            
            
            <!------------------------------------------------------------ Lead Data(No Converted and Prospect Data)  to Display ------------------------------------------------------------------------>   
       
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Lead" rendered="{!ld1 != false}" >
                    
                    <!-- Regarding the Boolean Value in Lead Object ---------------------------------------->       
                    <apex:pageBlockTable value="{!ldlist}" var="Leaddata" cellspacing="10">
                        
                        <apex:column style="width:100px" value="{!Leaddata.Name}" headerValue="Lead Name"/>
                        <apex:column style="width:100px" value="{!Leaddata.Status}" headerValue="Lead Status"/>
                        <apex:column style="width:100px" value="{!Leaddata.Owner.Name}" headerValue="Owner Name"/>
                        <apex:column style="width:100px" value="{!Leaddata.Lead_Owner_Role__c}" headerValue="Owner Role"/>
                        <apex:column style="width:100px" value="{!Leaddata.User_Mobile__c}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!Leaddata.Owner.Email}" headerValue="Owner Email"/>
                        <!----- OwnerId Field in Lead Object ----------------------------------------------->      
                       
                        <apex:column >
                            <apex:facet name="header">New Lead Owner</apex:facet>
                              <apex:inputField value="{!Leaddata.ownerId}" required="false" rendered="{!IF((Leaddata.Lead_Owner_Role__c ='Internal Sales Agent'||Leaddata.Lead_Owner_Role__c ='Internal Sales Team Lead'||Leaddata.Lead_Owner_Role__c ='Internal Sales Team Director'),false,true)}"/>
                        </apex:column> 
                        <apex:column headerValue="Change Ownership" >
                            <apex:inputCheckbox value="{!Leaddata.DUP_Update_Owner__c}"  label="Change Ownership" rendered="{!If((Leaddata.Lead_Owner_Role__c ='Internal Sales Agent'||Leaddata.Lead_Owner_Role__c ='Internal Sales Team Lead'||Leaddata.Lead_Owner_Role__c ='Internal Sales Team Director'),false,true)}"/> 
                        </apex:column> 
                        
                    </apex:pageBlockTable>
                    
                </apex:pageBlockSection>
            
            </apex:outputPanel> 
          
            
            <!------------------------------------------------------------ Lead 2 Data(No New, Assigned, Followup and Junk Data)  to Display ------------------------------------------------------------------------>   
       
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="SalesOwner leads" rendered="{!ld2 != false}" >
                    
                    <!-- Regarding the Boolean Value in Lead Object ---------------------------------------->       
                    <apex:pageBlockTable value="{!ldlist1}" var="lds" cellspacing="10">
                        
                        <apex:column style="width:100px" value="{!lds.Name}" headerValue="Lead Name"/>
                        <apex:column style="width:100px" value="{!lds.Status}" headerValue="Lead Status"/>
                        <apex:column style="width:100px" value="{!lds.Owner.Name}" headerValue="Owner Name"/>
                        <apex:column style="width:100px" value="{!lds.Lead_Owner_Role__c}" headerValue="Owner Role"/>
                        <apex:column style="width:100px" value="{!lds.User_Mobile__c}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!lds.Owner.Email}" headerValue="Owner Email"/>
                        <!----- OwnerId Field in Lead Object ----------------------------------------------->      
                       
                    </apex:pageBlockTable>
                    
                </apex:pageBlockSection>
            
            </apex:outputPanel> 
          
            <!------------------------------------------------------- Opportunity Data  to Display ---------------------------------------------------------------------------->             
       
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Opportunity" rendered="{!opp1 != false}">
                    
                    <!--- Values to display in Opportunity Object---------------------------------------->
                    <apex:pageBlockTable style="width:150%" value="{!opplist}" var="opp"  cellspacing="10">

                        <apex:column style="width:100px" value="{!opp.name}" />  
                        <apex:column style="width:100px" value="{!opp.StageName}" headerValue="Opportunity Stage"/>
                        <apex:column style="width:100px" value="{!opp.owner.Name}" headerValue="Owner"/>  
                        <apex:column style="width:100px" value="{!opp.owner.UserRoleId}" headerValue="Owner Role"/>
                        <apex:column style="width:100px" value="{!opp.owner.MobilePhone}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!opp.owner.Email}" headerValue="Owner Email"/>   
                        <!----- OwnerId Field in Lead Object ----------------------------------------------->      
                        
                    </apex:pageBlockTable>
                </apex:pageBlockSection>
            </apex:outputPanel>

            <!---------------------------------------------------------- Account Data  to Display ---------------------------------------------------------------------->             
    <!--     
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Account" rendered="{!ac1 != false}">  -->
 
                    <!--- Values to display in Account Object---------------------------------------->
               <!--     <apex:pageBlockTable style="width:150%" value="{!aclist}" var="ac"  cellspacing="10">
 
                        <apex:column style="width:100px" value="{!ac.Name}" />  
                        <apex:column style="width:100px" value="{!ac.owner.Name}" headerValue="Owner"/>
                        <apex:column style="width:100px" value="{!ac.owner.UserRoleId}" headerValue="Owner Role" />
                        <apex:column style="width:100px" value="{!ac.owner.MobilePhone}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!ac.owner.Email}" headerValue="Owner Email"/>   
                        
                         
                    </apex:pageBlockTable>
                </apex:pageBlockSection>
            </apex:outputPanel>  -->
            
            <!------------------------------------------------------------- Contact Data  to Display --------------------------------------------------------------------->             
         
            <apex:outputPanel layout="block" styleClass="custom1">
                <apex:pageBlockSection title="Account / Contact" rendered="{!cn1 != false}">

                    <!---  Values to display in Contact Object-------------------------------------------->
                    <apex:pageBlockTable style="width:150%" value="{!cnlist}" var="con"  cellspacing="10">

                        
                        <apex:column style="width:100px" value="{!con.Name}" />  
                        <apex:column style="width:100px" value="{!con.owner.Name}" headerValue="Owner"/>  
                        <apex:column style="width:100px" value="{!con.owner.UserRoleId}" headerValue="Owner Role"/>
                        <apex:column style="width:100px" value="{!con.owner.MobilePhone}" headerValue="Owner Mobile"/>
                        <apex:column style="width:100px" value="{!con.owner.Email}" headerValue="Owner Email"/> 
                        
                         
                    </apex:pageBlockTable>
                </apex:pageBlockSection>
            </apex:outputPanel> 
            
            <!-------- End of logics ------------------------------------------------------------------------------->     
        </apex:pageBlock>
    </apex:form>
</apex:page>

Now i need to create a List Button On Lead List Page.
to access this Vf page.

Please provide me a solution.

Thanks and Regards,
Azar Khasim.
Hi Team,

In my org omnichannel set up is done and every time client to trying to connect the omnichanne chat, i would like to display the average wait time for responce. Please suggest how to proceed on this.

Regards,
Raghu
public with sharing class OpportunitylistViewCom {
    @AuraEnabled
    public static List<OpportunityLineItem> getOpportunityLineItem(Id accountId,String sortField, boolean isAsc){
        String query = 'Select id,Opportunity.Name,Opportunity.Account.name,Opportunity.RecordType.Name,Opportunity.type,Opportunity.Amount,Opportunity.StageName,Opportunity.Parent_Asset__r.InstallDate,Product_Name__c,UnitPrice,TotalPrice,ListPrice,End_Date__c,Related_To__c ';
            query += 'From OpportunityLineItem where Opportunity.AccountId =:accountId';
        if (sortField != '') {
            query += ' order by ' + sortField;
            if (isAsc) {
                query += ' asc';
            } else {
                query += ' desc';
            }
        }
        list <OpportunityLineItem> oppList1;
        try {
            oppList1 = Database.query(query);
            List < OpportunityLineItem > oppList = new List < OpportunityLineItem > ();
            for (OpportunityLineItem c: oppList1) {
                oppList.add(c);
            }
            return oppList;
        } 
        catch (Exception ex) {
            // for handle Exception
            return null;
        }
    }
   
    @AuraEnabled
    public static list < Attachment > fetchopportunity(Id accountId) {
        set<ID> oppIDs = new set<ID>();
        for(Opportunity opp :[Select id from opportunity where AccountId=:accountId]){
            oppIDs.add(opp.id);
        }
        list < Attachment > returnoppList = new List <Attachment> ();
        List < Attachment > lstopp = [select id,name,LastModifiedDate,CreatedBy.name,Parent.Name, Owner.Name, BodyLength from Attachment where ParentId IN:oppIDs];
        for (Attachment c: lstopp) {
            returnoppList.add(c);
        }
        return returnoppList;
    }
}

 
I'm no expert in writing apex codes and I've just got this code below to work in the sandbox environment. What this does is that it changes the case status to In Progress when an agent accepts a case from omni channel. I've tried to deploy it in production but its not letting me as I am getting an error for code coverage. I dont have any idea on how to write a test class for AgentWork as I can't find many detailed examples that I can relate my code and study to write it from scratch. 

trigger Omni_Work_Status on AgentWork (after update) {
    for ( AgentWork newAW : Trigger.new){

        AgentWork oldAW = Trigger.oldMap.get(newAW.Id);
        Boolean acceptedWork = oldAW.AcceptDatetime != newAW.AcceptDatetime;

        if ( acceptedWork ){

        String workitemId = newAW.WorkItemId;

        try{
            
            Case c = [SELECT Status FROM Case WHERE Id =: workitemId ];

            c.Status = 'In Progress';

            update c;

        } catch (exception e){

            //do nothing

            System.debug('error message: '+ e.getMessage());

            }
        }
    }
}
I have a lightning component which contains input fileds(checkbox and picklist). These fields are not related to any object. 
How can i pass the field values from component to JS controller on click of submit button??

NOTE: I cannot make use of Component.find() or aura:attribute as the fields on the component are populated through aura:iteration.
Any help would be highly appreciated.
  • March 08, 2020
  • Like
  • 0
I want these picklist values in ascending order.How to set picklist records in acending order ?Could you please help me on this ?
HII All,
         Next visit should be greater than 30 days than Appointment Created Date:
       Next_visit__c<(Date value(Created Date )+30)
But its Showing An Error i.e, Error: Syntax error. Found 'Date'
 
Hi,

I try to upload an apex class from the sandbox to the prod. and receiving following error:

System.NullPointerException: Attempt to de-reference a null object
Stack Trace: Class.ClsApplicationTrainingRequestController.getPickValues: line 57, column 1 Class.ClsAppTrainRequestController_Test.myUnitTest: line 52, column 1

The person who has created the custom code has left the company years ago and I have no apex skills. Can anyone please help me with this?

Apex Class
public class ClsApplicationTrainingRequestController {

    public Application_Training_Request__c appRequest {get;set;}
    public Id trainRecordType;
    
    public ClsApplicationTrainingRequestController(ApexPages.StandardController stdController){
        Id oppyId = System.currentPageReference().getParameters().get('oppyId');
        Opportunity oppy = [Select OwnerId,AccountId,Market_sub_Segment__c,Market_Segment__c,Id,Business_Unit__c,BNG_Strategic_Market__c 
                        From Opportunity where id=:oppyId];
        appRequest = new Application_Training_Request__c();
        if(oppyId != null){
            appRequest.opportunity_name__c = oppyId;
            //appRequest.market_segment__c = oppy.market_segment__c;
            //appRequest.market_subsegment__c = oppy.market_sub_segment__c;
            appRequest.business_unit__c = oppy.business_unit__c;
            appRequest.opportunity_owner__c = oppy.ownerid;
            //appRequest.bng_strategic_market__c = oppy.bng_strategic_market__c;
            appRequest.account_name__c = oppy.accountid;    
            
            List<OpportunityCompetitor> oppyCompetitorList = [SELECT OpportunityId, Id, CompetitorName FROM OpportunityCompetitor 
                        where OpportunityId =:oppyId];
            String competitors = '';
            Map<String,String> resutlMap = new Map<String,String>();
            System.debug('---oppyCompetitorList');
            for(OpportunityCompetitor oppyComp : oppyCompetitorList){
                System.debug(resutlMap + '---resutlMap' + oppyComp.competitorname);
                if(!resutlMap.containsKey(oppyComp.competitorname)){
                    if(competitors != ''){
                        competitors += ';'; 
                    }
                    competitors += oppyComp.competitorname; 
                    resutlMap.put(oppyComp.competitorname,oppyComp.competitorname);
                    System.debug(competitors + '----' + oppyComp.competitorname);
                }
            }
            appRequest.competitor__c = competitors;
        }
    }
    
    public List<RecordType> getRecordTypeList(){
        List<RecordType> recordList = [Select Name,Id,Description,developername From RecordType where SobjectType='Application_Training_Request__c'];
        for(RecordType rt : recordList){
            if('Training_Request'.equals(rt.developername)){
                trainRecordType = rt.id;    
            }
        }
        return recordList;
    }
    public List<selectOption> getPickValues(Sobject object_name, String field_name, String first_val) {
        List<selectOption> options = new List<selectOption>(); //new list for holding all of the picklist options
        if (first_val != null) { //if there is a first value being provided
           options.add(new selectOption(first_val, first_val)); //add the first option
        }
        Schema.sObjectType sobject_type = object_name.getSObjectType(); //grab the sobject that was passed
        Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject
        Map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject
        List<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject
        for (Schema.PicklistEntry a : pick_list_values) { //for all values in the picklist list
                      
             options.add(new selectOption(a.getValue(), a.getLabel())); //add the value and label to our final list
        }
        System.debug('--options' + options);
        return options; //return the List
        
    }

    public PageReference saveRequest(){
        try{
            system.debug('www saveRequet appRequest : ' + appRequest);
            if(appRequest.recordtypeid != trainRecordType){
                //appRequest.request_type__c = 'Sample Analysis';
                //appRequest.permission_on_sample_preparation__c = 'permitted';
                //appRequest.sample_status_indicator__c = 'received';
            }
            insert appRequest;
            System.debug('--appRequest---' + appRequest);
            PageReference requestPage = new ApexPages.StandardController(appRequest).view();
            requestPage.setRedirect(true);
            return requestPage;
        }catch(Exception ex){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ex.getStackTraceString()));
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage()));
            System.debug('Method---:saveRequest-- linenumber :' + ex.getLineNumber() + '---message:' + ex.getMessage());
            return null;
        }
    }
}



Test Class
/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 * 
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class ClsAppTrainRequestController_Test {

    /*static testMethod void myUnitTest() {
        Account acc = new Account();
        acc.Name = 'jinbo test accoutn13';
        insert acc;
        
        Opportunity oppy = new Opportunity();
        oppy.AccountId = acc.Id;
        oppy.StageName = 'Closed Lost';
        oppy.Name = 'test oppy name';
        oppy.CloseDate = system.today();
        insert oppy;
        OpportunityCompetitor oppyComp = new OpportunityCompetitor();
        oppyComp.competitorname = 'Atominstitut Wien';
        oppyComp.opportunityid = oppy.id;
        insert oppyComp;
        
        OpportunityCompetitor oppyComp2 = new OpportunityCompetitor();
        oppyComp2.competitorname = 'Bowman';
        oppyComp2.opportunityid = oppy.id;
        insert oppyComp2;
        
        List<RecordType> recordList = [Select Name,Id,Description,developername From RecordType where SobjectType='Application_Training_Request__c' and developername='Application_Request'];
        System.currentPageReference().getParameters().put('oppyId',oppy.id);
        ApexPages.StandardController extController = new ApexPages.StandardController(new Application_Training_Request__c());
        ClsApplicationTrainingRequestController contr = new ClsApplicationTrainingRequestController(extController);
        contr.getRecordTypeList();
        contr.saveRequest();
        contr.getPickValues(new Application_Training_Request__c(),'request_type__c',null);
        if(recordList != null && !recordList.isEmpty())
            contr.appRequest.recordtypeid = recordList.get(0).id;
    }*/
}

Thanks in advance!


 
So I'm new to writing apex triggers and need to push a few into production. My trigger code is: 
 
trigger Days_Open on Contact (after insert,after update) {
    List<account> li=new list<Account>();
    List<Id> ids = new List<Id>();
    for(Contact c: trigger.new)
        ids.add(c.AccountId);
    Map<Id, Account> accountMap = new Map<Id, Account>([Select Id, Phone From Account Where Id In :ids]);
    for(Contact c: trigger.new)
    {
        Account a = accountMap.get(c.AccountId);
        if(a != null)
        {
            a.Days_Open__c = c.Days_Open__c;
            li.add(a);
        }
    }
    update li;
}
How do I write a test class? Trigger works in the environment. I need to have it check that when a contact record is saved it copies it to the account that the contact is related too. I currently cannot push into production as code coverage is at 0%
 
I need to expose a visualforce page on a custom object( Support Request) when SLA is breached for that support Request.
When Today date>= SLA Due Details, visualforce component on the Support Request page should show below message
"SLA Breached, please treat this on priority"

I have created below VF page and trying to expose on the page layout:

<apex:page standardController="Support_Request__c"> if (SLA_Details__c == null) { ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'SLA Breached')); return null; } </apex:page>

But its not working fine, Kindly suggest

trigger DateofBirth on Account (before insert) {
    for(Account a:trigger.new){
        if(a.Date_of_Birth__c!=NUll && ((system.today()- a.Date_of_Birth__c)/365 <=18)){
            a.Date_of_Birth__c.adderror('Age should be more than 18');
        }
    }
}

 

error i am facing:

Date expressions must use Integer or Long