• pavan kumar 177
  • NEWBIE
  • 5 Points
  • Member since 2015

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 24
    Questions
  • 23
    Replies
I'm currently overriding the edit button with the lightning record edit component for a custom object named 'Schedule' which has a lookup relationship with the lead record. My requirement is to get lead record fields and display them on the form. I believe we can get the fields through force: record data but how to get & pass the lookup record id. Is there a better anyway to handle this?
For Reference:

User-added image
I have a requirement to set up a scheduled batch that will run every day & calculate the duration between the last date of opportunity stage changes to the current date.
  1. Duration >=25 & Duration <30(Send Email & update opportunity fields)
  2. Duration >30 (Update Stage,Other fields)
My code is working as expected but i don't have any clue cover these use cases because OpportunityHistory object is not writeable. Is there any way to handle this use case like setting up mock test or anything.

Batch Class:
 
global class StageAge implements Database.Batchable<sObject>  
{
    public static List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    public static id owea = [select Id,address from OrgWideEmailAddress where Address = 'info@a.com' Limit 1].id;
    public Static Id Inboundtemplate = [select id from EmailTemplate where name ='Handle CloseDate' Limit 1].id;
    global Database.QueryLocator start(Database.BatchableContext bc)
    {
       return Database.getQueryLocator('Select id from opportunity where isclosed=false AND Team__c=\'Bangalore Team\''+
                                      'AND StageName != \'Nurture\''); 
    }
    global void execute(Database.BatchableContext bc, List<Opportunity> OpportunityList)
    {
        Map<Id,Opportunity> UserDetails = new Map<Id,Opportunity>();
        If(OpportunityList <> null && !OpportunityList.isEmpty())
        {
            for(opportunity opps:[Select id,ownerid,name,Owner.FirstName,Owner.LastName from opportunity where id in:OpportunityList])
            {
                UserDetails.put(opps.id,opps);
            }
        }
        System.debug('Details Opportunity'+OpportunityList.size());
        Map<Id,Integer> Opportunityids = new Map<Id,Integer>();
        List<Opportunity> Nurtureupdate = new List<Opportunity>();
        Map <Id,OpportunityHistory> LastStage =new Map <Id,OpportunityHistory>();
        For(OpportunityHistory opps:[Select id,OpportunityId,CreatedDate from OpportunityHistory
                                     where OpportunityId IN:OpportunityList ORDER BY CreatedDate DESC NULLS First])
        {
            If(!LastStage.containsKey(opps.OpportunityId))
            {
                System.debug('Inside Loop'+opps.OpportunityId);
                System.debug('Create date '+opps.CreatedDate);
                LastStage.put(opps.OpportunityId,opps);  
                Integer Duration=0;
                //Datetime MainCreateddate = opps.CreatedDate;
                Duration=opps.CreatedDate.Date().daysBetween(Date.today());
                System.debug('Duration Details'+Duration);
                If(Duration >= 25 && Duration < 30)
                {
                    System.debug('Inside Duration');
                    EmailDispatcher(opps.OpportunityId,UserDetails.get(opps.OpportunityId).ownerid,UserDetails.get(opps.OpportunityId).name
                                   ,UserDetails.get(opps.OpportunityId).Owner.FirstName,UserDetails.get(opps.OpportunityId).Owner.Lastname);
                    Opportunityids.put(opps.OpportunityId,Duration);
                }
                If(Duration >30)
                {
                    Opportunityids.put(opps.OpportunityId,Duration);
                }
            }          
        }
        if(mails!=null && !mails.isEmpty())
        {
            System.debug('Its working');
            Messaging.sendEmail(mails);
        }
        If(Opportunityids <> null && !Opportunityids.isEmpty())
        {
            For(Opportunity oppupdate:[Select id,stagename from opportunity where id in:Opportunityids.keyset()])
            {
                System.debug('Opportunity_Duration_Before_Check'+Opportunityids.get(oppupdate.id));
                If(Opportunityids.get(oppupdate.id) >30)
                {
                    Opportunity Oppaddition     = new Opportunity();
                    Oppaddition.id              = oppupdate.id;
                    Oppaddition.stagename       = 'Nurture';
                    System.debug('******Opportunity>30'+Opportunityids.get(oppupdate.id));
                    Oppaddition.Stage_Age__c    = Opportunityids.get(oppupdate.id); 
                    Nurtureupdate.add(oppaddition);
                }
                System.debug('**********Opportunity_Before_Check<30'+Opportunityids.get(oppupdate.id));
                If(Opportunityids.get(oppupdate.id) >= 25 && Opportunityids.get(oppupdate.id) < 30)
                {
                    Opportunity Oppaddition     = new Opportunity();
                    Oppaddition.id              = oppupdate.id; 
                    System.debug('**********Opportunity<30'+Opportunityids.get(oppupdate.id));
                    Oppaddition.Stage_Age__c    = Opportunityids.get(oppupdate.id); 
                    Nurtureupdate.add(oppaddition);
                }                
            }
            If(Nurtureupdate <> null && !Nurtureupdate.isEmpty())
            {
                update Nurtureupdate;
            }
        }
    }
    Public Static void EmailDispatcher(Id OpportunityDetails,Id Target,String Opportunityname,String Firstname,String Lastname)
    {
        System.debug('Target details'+Target);
        System.debug('Inside Dispatcher');
        System.debug('OpportunityDetails'+OpportunityDetails);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        //mail.settemplateid(Inboundtemplate);
        mail.setTargetObjectId(Target);
        mail.setTreatTargetObjectAsRecipient(true);
        //mail.setToAddresses(new String[] {'toml@a.com'});
        mail.setOrgWideEmailAddressId(owea);
        mail.setUseSignature(false);
        mail.setSaveAsActivity(false);
        mail.setReplyTo('marketing@a.com');
        mail.setsubject('Update CloseDate of Opportunity Name '+Opportunityname);
        String body = 'Hi '+Firstname+' '+Lastname+','+'<br/>'+'<br/>';
        body += 'Opportunity Name '+Opportunityname+'<br/>';
        body += 'Have we closed this one? Please update the Close date accordingly.'+'<br/>';
        body += 'For More details'+'<a href="'+OpportunityDetails+'">'+'Click Here'+'</a>'+'<br/>'+'<br/>';
        body += 'Thanks you again'+'<br/>';
        body += 'Team Azuga'+'<br/>'+'<br/>';
        mail.setHtmlBody(body);
        mails.add(mail);
    }
    global void finish(Database.BatchableContext bc)
    {
        
    }
}

 
Currently, I'm working on overriding standard pages to vf on case object which has different record types.
My problem is overriding standard layout to custom vf page for record detail page.
I don't want to use the detail tag because I need to customize the details and I need related lists with hover links.
Please guide me is there any way to achieve this.
My Code:
<apex:page standardController="case" extensions="Risk_Alignment" standardStylesheets="true">
<style type="text/css">

 </style>
 <apex:sectionHeader title="{!$ObjectType.Case.label}" subtitle="{!case.casenumber}" printUrl="Print" help="Help for this Page"/>
 <button id="myButton1" class="btn" onclick="myFunction()" >Show</button>
<script>
function myFunction() {
    var x = document.getElementById('myDIV');
    var y = document.getElementById('myButton1');
    if (x.style.display === 'none') {
        y.innerHTML = 'Hide';
        x.style.display = 'block';        
    } else {
        y.innerHTML = 'Show';
        x.style.display = 'none';
    }
}
</script>
<div id="myDIV" style="display:none">
<chatter:feed entityId="{!$User.Id}" />
</div>
<apex:pageBlock title="Case" mode="view">
   <apex:pageBlockButtons styleClass="false" >
   <apex:form >
   <apex:commandButton styleClass="false" value="Save" action="{!save}"/>
   <apex:commandButton value="Save & Close" action="{!save}"/>
   <apex:commandButton value="Save & New" action="{!save}"/>
   <apex:commandButton value="Cancel" action="{!cancel}"/>
   </apex:form>
   </apex:pageBlockButtons>
   </apex:pageBlock>
</apex:page>

 
public class AuthCallout {
    public void basicAccessTokenGeneration() {
     HttpRequest req = new HttpRequest();
     req.setEndpoint('https://');
     req.setMethod('POST');

     // Specify the required username and password to access the endpoint
     // As well as the header and header information

     String username = '';
     String password = '';
     String vendor   = '';
     String businessunit ='';
     String application ='';

     Blob headerValue = Blob.valueOf(application + '@' + vendor + ':' + businessunit);
     String authorizationHeader = 'BASIC ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);


    JSONGenerator gen = JSON.createGenerator(true);    

    gen.writeStartObject();      
    gen.writeStringField('grant_type ', 'password');
    gen.writeStringField('username', username);
    gen.writeStringField('password',password);
    gen.writeStringField('scope','');
    gen.writeEndObject();
    String jsonS = gen.getAsString();
    system.debug('DAta in '+str);
    system.debug('Data in gen'+jsonS);
    req.setBody(jsonS);
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  

     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
        System.debug(res.getStatusCode());
        System.debug(res.getBodyDocument());
   }
}

'm new to integration. I am going to generate an access token for the third-party application.
I tried to build following javascript request in sfdc.

But the response body is blank. I need to retrieve access token & other things to call specific endpoint in another class.
Please let me know where i did wrong

I am searlize JSON string also while sending the body

They gave same code request sample in java format like below.

Sample request
var result = {};
var application = "";
var vendor = "";
var businessunit = "";
var user = "";
var pass = "";
var authCode = window.btoa(application + "@" + vendor + ":" + businessunit);
$.ajax({
    "url": 'https://',
    "type": 'post',
    "contentType": 'application/json',
    "dataType": 'json',
    "headers": {
        'Authorization': 'basic ' + authCode
    },
    "data": JSON.stringify({
    "grant_type": 'password',
    "username": user,
    "password" : pass,
    "scope": 'AdminApi AgentApi AuthenticationApi PatronApi RealTimeApi'
    }),
    "success": function (resp) {
        result.access_token = resp.access_token;
        result.token_type = resp.token_type;
        result.resource_server_base_uri = resp.resource_server_base_uri;
        result.expires_in = resp.expires_in;
        result.refresh_token = resp.refresh_token;
        result.scope = resp.scope;
        result.refresh_token_server_uri = resp.refresh_token_server_uri;
    },
    "error": function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Failed to retrieve token.\n" + XMLHttpRequest.status + ' ' 
            + XMLHttpRequest.statusText);
    }
});

My Apex

 
I have a requirement to provide customizable timelines to close a case with in specified time.

So, i set up entitlement process but my requirement is to apply milestone for specific cases with specific record owner.If i remove case owner from below criteria it's working fine.But if i include it is not working don't know where i went wrong.

Like below:

User-added image
In our organsation multiple teams are working on sales & in our sfdc organisation we are following PST time zone.
So, we need to know how many opportunities created between 1:30 pm PST to 5:00 PM on same day.
For example:
20/11/17 1:30PM PST 20/11/17 5:00 PM PST
Any possibility to calculate in sfdc
My formula would be:
I took TZoffset is 8/24 because my organisation time zone would be (GMT-08:00) Pacific Standard Time (America/Los_Angeles)
And some opportunities i am facing an issue because Day/light saving and now i am only able to capture time.
IF( 
OR( 
VALUE( MID( TEXT( CreatedDate - 8/24), 12, 2 ) ) = 0, 
VALUE( MID( TEXT( CreatedDate - 8/24 ), 12, 2 ) ) = 12 
), 
"12", 
TEXT( VALUE( MID( TEXT(CreatedDate - 8/24 ), 12, 2 ) ) 
- 
IF( 
VALUE( MID( TEXT( CreatedDate - 8/24 ), 12, 2 ) ) < 12, 
0, 
12 
) 
) 
)& 
":" & 
MID( TEXT( CreatedDate - 8/24 ), 15, 2 ) 
& ":" & 
MID( TEXT( CreatedDate - 8/24 ), 18, 2 ) 
& " " & 
IF( 
VALUE( MID( TEXT( CreatedDate - 8/24 ), 12, 2 ) ) < 12, 
"AM", 
"PM" 
)

 
 am sending sample survey email to users whenever accounts meets particular criteria.

I created a apex class and iam accessing contacts and sending contact details to below SendEmail method.Now i am attaching a link within email template through HTML body but i dont want to send long link to the user.

Is there any way to hyperlink above link to small text or clickable image.

Like Below:
 
public Static void sendMail(Id accountdetails,String Emaildetails,Id Contactdetails,Id CaseId,String Customername,String Accountsname)
    {
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        List<String> sendTo = new List<String>();
        sendTo.add(Emaildetails);
        mail.setToAddresses(sendTo);
        mail.setReplyTo('pavank@azuga.com');
        mail.setSenderDisplayName('Azuga Telematics');
        mail.setsubject('Invitation to participate in survey');
        String body = 'Hi '+Customername+','+'<br/>'+'<br/>';
        body += 'Account Name:'+'<br/>'+'<br/>';
        body += Label.Churn_Site_Details+'&cId='+Contactdetails+'&caId='+CaseId;
        mail.setHtmlBody(body);
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
        inspectResults(results,accountdetails);
    }

 
Hi friends i got a requirement to summarize call duration.So,I created a custom field with Call Duration(Minutes).
IF((MOD(CallDurationInSeconds/60,1)*60) > 10, VALUE(TEXT(FLOOR( CallDurationInSeconds/60)) + "." + TEXT(FLOOR(MOD( CallDurationInSeconds/60,1)*60) )), VALUE(TEXT(FLOOR( CallDurationInSeconds/60)) + ".0" + TEXT(FLOOR(MOD( CallDurationInSeconds/60,1)*60) )) )

Now i am able to summarize but it's showing everything in minutes like for 1 hour 50 minutes.It's showing 150.Please i want like in hours and minutes format.
Got a requirement like to calculate average in account based on particular record type of case. My requirement is:

I have a field called ARP in account currency. I want to calculate overall average of ARP field in particular record type called customer order whether Case details either new or add-on.

So I'm trying write a trigger a trigger.

Everything is working fine in sandbox but in production when i update any old cases it's not updating accurately.If i do update in sandbox is working fine.

And for example there is case with above criteria like 18.55.But it updating 6.55.When i check from random accounts it  is calculating average with all cases to a respective account.

When i try to create any cases with new accounts it is working fine.Please help me guys to sort out.

trigger ForARPU on case (after insert,after update,after delete) 
   {
       if(Trigger.isAfter && trigger.isInsert || Trigger.isAfter && trigger.isUpdate) 
    {     
        //It will call a static method called ARPUInsert in ARPUCases class.
        ARPUCases.ARPUInsert(Trigger.New);

    }
}

Handler trigger

public static void ARPUInsert(List<Case>  CaseTriggers)
    {
        /** 
         * This method is to caluclate average of all ARPU amounts with case have customer order recordtype
         * as well as case details with either ADD-On (OR) New Subscription and update in related account
         * field called ARPU. 
         * This method will fire only when any case with record type called customer order is created as well updated. 
        */
        Id recordTypeId = [Select Id From RecordType Where DeveloperName = 'Customer_Order'].Id;
        List<Account> Accountstoupdate =new List<Account>();
        List<Case> CaseIDs = new List<Case>();
        for (Case s : CaseTriggers)
        {
            if(s.RecordTypeId == recordTypeId && (s.Case_Details__c =='New Subscription' || s.Case_Details__c =='Add On') ) 
            {
                    // Loop through and add caseId's to the list.
                    CaseIDs.add(s);
            }
        }
        /** @Var CaseAccountIds - to get accountId's of cases with list called CaseIDs */
        set<Id> CaseAccountIds = new set<Id>();
        for(Case c : [SELECT Id,ARPU__c,accountId FROM Case WHERE Id IN :CaseIDs])
        {
            // Loop through and add AccountId's to the list.
            CaseAccountIds.add(c.AccountId);
        }
        /** @Var Accountswithcases-to get account details to caluclate average */
        /** @Var results-to get average of particular account based on the cases */
        List<Account> Accountswithcases = [select Id,name,ARPU__c  from Account where id =:CaseAccountIds];
        Map<Id, AggregateResult> results = new Map<Id, AggregateResult>(
            [SELECT AccountId Id, AVG(ARPU__c) average FROM Case WHERE AccountId = :Accountswithcases GROUP BY AccountId]);
        For(account a1: Accountswithcases) 
        {
            if(results.get(a1.Id) != null) 
            {
                // Loop through aggregate results array and typecast the average of ARPU and update in account level.
                a1.ARPU__c = (Decimal)results.get(a1.Id).get('average');
                Accountstoupdate.add(a1);
            }
        }
        if(Accountstoupdate.size()>0) 
        {
            // DML statement to update all the accounts related with cases
            update Accountstoupdate;
        }
}

 
got a requirement like to calculate average in account based on particular record type of case. My requirement is:

I have a field called ARP in account currency. I want to calculate overall average of ARP field in particular record type called customer order whether Case details either new or add-on.

So I'm trying write a trigger a trigger.

Everything is working but after delete event is not working means.

Example when i create a case with ARPU will be 21.And if i delete the case it's still showing 21 in account level.Even i am trigger.old in trigger to handler class.


My trigger would be 

trigger ForARPU on case (after insert,after update,after delete) 
{  
    if(Trigger.isAfter && trigger.isInsert || Trigger.isAfter && trigger.isUpdate ) 
    {      
        //It will call a static method called ARPUInsert in ARPUCases class.
        ARPUCases.ARPUInsert(Trigger.New);
    
    }
    if(Trigger.isAfter && trigger.isDelete) 
    {     
        //It will call a static method called ARPUInsert in ARPUCases class.
        ARPUCases.ARPUDelete(Trigger.Old);
    
    }
}

Handler class would be My debug Logs

/**
 * This class is used to calculate average of Arpu in customer order record type
 * with cases details either Add-on or New subscription and update in Related Account field called ARPU.
 * This class is fire whenever record type called customer order case has been inserted or updated or deleted.
 * @author  Pavan Kumar
 * @since   2016-09-28 
*/
public class ARPUCases 
{
    /** @var recordTypeID - is to filter cases with particular record type */
    /** @var Accountstoupdate - is to update the particular accounts */
    /** @var CaseIDs - is to retrive all related case id's */
     
    public static Set<Account> accSet = new Set<Account>();
    
    public static void ARPUInsert(List<Case>  CaseTriggers)
    {
        /** 
         * This method is to caluclate average of all ARPU amounts with case have customer order recordtype
         * as well as case details with either ADD-On (OR) New Subscription and update in related account
         * field called ARPU. 
         * This method will fire only when any case with record type called customer order is created as well updated. 
        */
        
        if (Trigger.isInsert || Trigger.isUpdate) 
        {
            Id recordTypeId = [Select Id From RecordType Where DeveloperName = 'Customer_Order'].Id;
     List<Account> Accountstoupdate =new List<Account>();
     List<Case> CaseIDs = new List<Case>();
            for (Case s : CaseTriggers)
            {
                if(s.RecordTypeId == recordTypeId && s.Case_Details__c =='New Subscription' || s.Case_Details__c =='Add On' ) 
                {
                    // Loop through and add caseId's to the list.
                    CaseIDs.add(s);
                }
            }
            /** @Var CaseAccountIds - to get accountId's of cases with list called CaseIDs */
            set<Id> CaseAccountIds = new set<Id>();
            
            for(Case c : [SELECT Id,ARPU__c,accountId FROM Case WHERE Id IN :CaseIDs])
            {
                // Loop through and add AccountId's to the list.
                CaseAccountIds.add(c.AccountId);
            }
            /** @Var Accountswithcases-to get account details to caluclate average */
            /** @Var results-to get average of particular account based on the cases */
            List<Account> Accountswithcases = [select Id,name,ARPU__c  from Account where id =:CaseAccountIds];
            Map<Id, AggregateResult> results = new Map<Id, AggregateResult>(
                [SELECT AccountId Id, AVG(ARPU__c) average FROM Case WHERE AccountId = :Accountswithcases GROUP BY AccountId]);
            For(account a1: Accountswithcases) 
            {
                if(results.get(a1.Id) != null) 
                {
                    // Loop through aggregate results array and typecast the average of ARPU and update in account level.
                    a1.ARPU__c = (Decimal)results.get(a1.Id).get('average');
                    Accountstoupdate.add(a1);
                }
                
            }
            if(Accountstoupdate.size()>0) 
            {
                // DML statement to update all the accounts related with cases
                update Accountstoupdate;
            }
        }
    }
    public static void ARPUDelete(List<Case>  CaseTriggers) 
    {
        /** 
         * This method is to caluclate average of all ARPU amounts with case have customer order recordtype
         * as well as case details with either ADD-On (OR) New Subscription and update in related account
         * field called ARPU. 
         * This method will fire only when any case with record type called customer order is deleted. 
        */
        
        if (Trigger.isDelete)
        {
            Id recordTypeId = [Select Id From RecordType Where DeveloperName = 'Customer_Order'].Id;
     List<Account> Accountstoupdate =new List<Account>();
     List<Case> CaseIDs = new List<Case>();
            for (Case s : CaseTriggers)
            {
                if(s.RecordTypeId == recordTypeId && s.Case_Details__c =='New Subscription' || s.Case_Details__c =='Add On') 
                {
                    // Loop through and add caseId's to the list.
                    CaseIDs.add(s);
                }
            }
            System.debug('Data in  CaseIDs:'+ CaseIDs.size());
            System.debug('Data in  details CaseIDs:'+ CaseIDs);
            /** @Var CaseAccountIds - to get accountId's of cases with list called CaseIDs */
            set<Id> CaseAccountIds = new set<Id>();
            for(Case c : CaseTriggers)
            {
                 // Loop through and add AccountId's to the list.
                CaseAccountIds.add(c.AccountId);
            }
            System.debug('After Data in  CaseAccountIds:'+ CaseAccountIds.size());
            System.debug('After Data Details in  CaseAccountIds:'+ CaseAccountIds);
            /** @Var Accountswithcases-to get account details to caluclate average */
            /** @Var results-to get average of particular account based on the cases */
            List<Account> Accountswithcases = [select Id,name,ARPU__c  from Account where id =:CaseAccountIds];
            Map<Id, AggregateResult> results = new Map<Id, AggregateResult>(
                [SELECT AccountId Id, AVG(ARPU__c) average FROM Case WHERE AccountId = :Accountswithcases GROUP BY AccountId]);
            System.debug('Results:'+ results.size());
            System.debug('Data in Accountswithcases:'+ Accountswithcases.size());
            For(account a1: Accountswithcases) 
            {
                if(results.get(a1.Id) != null ) 
                {
                    // Loop through aggregate results array and typecast the average of ARPU and update in account level.
                    a1.ARPU__c = (Decimal)results.get(a1.Id).get('average');
                    Accountstoupdate.add(a1);
                }
            }
            System.debug('After Results:'+  Accountstoupdate.size());
            System.debug('Size of the Results:'+  Accountstoupdate);
            if(Accountstoupdate.size()>0) 
            {
                // DML statement to update all the accounts related with cases.
                update Accountstoupdate;
            } 
        }
    }
}

I am attaching my debug logs
I got a requirement like to calculate average in account based on particular record type of case. My requirement is:

I have a field called ARP in account currency. I want to calculate overall average of ARP field in particular record type called customer order whether Case details either new or add-on.

So I'm trying write a trigger a trigger.

ARPu field in case is a formula currency data type.In account also i had created Arpu name with currency(5,2).

But i am getting a difference in average. For sample scenario: 41.51 & 94.51
Actual average for above scenario like 67.5.But, i am getting 139.51

trigger ForARPU on case (after delete, after insert) 
{  
  Id recordTypeId = [Select Id From RecordType Where DeveloperName = 'Customer_Order'].Id;
    List<Account> Accountstoupdate =new List<Account>();
    List<Case> CaseIDs = new List<Case>();
    for (Case s : Trigger.new)
    {
        if(s.RecordTypeId == recordTypeId && s.Case_Details__c =='New Subscription' || s.Case_Details__c =='Add On' ) 
        {
            CaseIDs.add(s);
          
        }
    }
    set<Id> setCaseIds = new set<Id>();
    for(Case c : [SELECT Id,ARPU__c,accountId FROM Case WHERE Id IN :CaseIDs]){
        setCaseIds.add(c.AccountId);
    }
    List<Account> MList = [select Id,name,ARPU__c  from Account where id =:setCaseIds];
    List <aggregateResult> groupedResults = [select sum(ARPU__c)aver from case where AccountId =: MList group By AccountId];
    Decimal decimalRevenue = 0;
    For(account a1: MList) {
        for (AggregateResult ar : groupedResults) 
        {
        String str = '' + ar.get('aver') ;
        decimalRevenue = Decimal.ValueOf(str) ;
        System.debug('decimalRevenue ::::: ' + decimalRevenue) ;
        a1.ARPU__c  = decimalRevenue;
        }
        Accountstoupdate.add(a1);
    }
    if(Accountstoupdate.size()>0) {
        update Accountstoupdate;
    }
}

I unable to find the problem
Hi friends i have a standard approval process in account.And in some scenarios the accounts submitted for approval multiple times.So, my requirement is to create a report for approvals in account.So, i create a custom report type but i need fields in account object.

So, for this requirement i need to add another child object to the account.And try to create a record when in goes for approval as specified below link

https://cherfeldman.blogspot.in/2014/01/potential-solution-for-reporting-on.html?showComment=1472502144116#c9027830380141607440

But,in my case is standard approval.User manually submits record for approval.So,I am confused to solve this issue.Please provide your suggestions for this requirement.
Hi Friends i got a requirement like whenever a case is created (Or) edited with specific criteria.I need to update specific field in opportunity.
So,for cases & opportunities have lookup relationship.But my requirement is single opportunities have multiple cases means we can use single opportunity in multiple cases.

I don't want to lose my data in opportunity if i can assign same opportunity in another case.

So,i came with process builder.

I do it like when a specific condition met.it updates a field in opportunity called

Churned units = Churned units+field in cases;

It's working only with one field.

For reference:

User-added image
I got a requirement like I have case record type called customer.Whenever any case is created with specific set of fields.i need to update specific field in opportunity.
User-added image
So,In that record type Look up relationship is there with opportunity.So, i write a process in process builder it is not updating anything.Even i met the criteria.

for reference: 

User-added image
I need to calculate days between two fields.

So I use daysBetween to complete when I try to do with two dates it's working fine.

But, when I try with list(or) map  it throws an error like:

Method does not exist or incorrect signature: [Date].daysBetween(List)

For reference my code:

public date closedates;
Public Long details;
List<Case> c=new List<case>();
List<Integer> Values=new List<Integer>();
//Integer Value=0;
List<Date> Churndate=new List<Date>();
List<Date> closedatesd=new List<Date>();
c=[Select Id,Date_Order_Received__c,accountId from case where RecordTypeId = '01290000000sF3L'];
System.debug('Data in Case '+c);
List<Id> accountIds= new List<Id>();
List<Account> accounts=new List<Account>();
List<Id> opps=new List<Id>();
List<Date> Oppsdate= new List<Date>();
for(Case cl:c) {
accountIds.add(cl.accountId);
//Churndate=cl.Date_Order_Received__c;
Churndate.add(cl.Date_Order_Received__c);
}
System.debug('Date value in '+churndate);
for(Account ao:[Select Id,name,(select Id,name,CloseDate from opportunities) from account where Id in:accountIds]) {
for(Opportunity opp : ao.opportunities) {
opps.add(opp.Id);
//details=closedates.daysBetween(Churndate);
**Values.add(opp.CloseDate.daysBetween(Churndate));**
//Other Operation you want to perform with every opportunity
}
}
 Hi Friends I'm facing a critical issue.like lot of accounts had ownership changes automatically.And all these accounts are showing account owner last modified by this user.We didn't set up any sharing rules or field update in accounts.Can anyone help me resolve this issue.

And we write an apex class in a custom object called bi in that object we have a common field in this and account.based on this field whenever it updated we automatically update the same field in account. But we didn't touch anything related to change the ownership of the account.

Any help is appreciated
I got a requirement like to create reports for activities.i have user able to view all accounts and Opportunities.But he can't able view all activities while creating reports.I don't why it will not work.Any help is appreciated.

And user in a different role hierarchy.Any solutions
Hi friends i am new to sfdc.I stuck in a problem called In case object we have 20 record types are avilable.We had created
some custom fields and we had using some fields in multiple record types.But my problem is i didn't create these recordtypes so
While i want to customize any one of these fields.I am trying to go and search each and every record rype layout.I am wasting lot of time while 
doing this everytime.Is there any way to know whether a picklist avilable in how many layouts or recordtypes.Please help me.
Hi I'm new to sales force development.I got a requirement like whenever opportunity owner is changed a custom field is to updated based on opportunity owner.I wrote a trigger it works fine.And i also write a test class for this trigger.i got 95% coverage my problem is to check whether this one handles multiple records and when i try to check that custom whether update or not with using system.assert equals fail.Please help me

For reference:

My apex class:

public class OpportunityTeamUpdate {
    public static void OpportunityMapping(List<Opportunity>  TriggerLeads) {
        /** @var ownerMap - map of Owner Ids to their matching Owner Record */
        System.debug('IN trigger ' +TriggerLeads);
    Map<Id,User> ownerMap;
        opportunity o=new opportunity();
    /** @var oppOwnerIds - set of Opportunity Owner Ids from the inserted / updated records */
    Set<Id> oppOwnerIds = new Set<Id>();
    /** @var nameOfOwner - will hold the name of the Oppturnity Owner */
    String nameOfOwner;
    String owners,ownerstemp;
    owners = Label.Special_Team;
    List<String> parts = owners.split(',');
        System.debug('special team ' +parts);
    ownerstemp = Label.Infinity;
    List<String> partstemp = ownerstemp.split(',');

    for(Opportunity opps : TriggerLeads){ // loop through all updated/inserted opps
        oppOwnerIds.add(opps.OwnerId); // add the owner id to the set of owner ids
        System.debug('Opportunity Id'+opps.OwnerId);
    }

    ownerMap = new Map<Id,User>([SELECT Id, Name FROM User WHERE Id IN :oppOwnerIds]);

    for(Opportunity opps : TriggerLeads){ // loop through the updated/inserted opps again
        nameOfOwner = ownerMap.get(opps.OwnerId).Name; // use the opportunity owner id to grab the record from the map
        for(String s:parts) {
        if(s.equals( nameOfOwner)) {
            opps.Team_Name__c ='Avengers';
            }
        }
        for(String s:partstemp) {
        if(s.equals( nameOfOwner)) {
            opps.Team_Name__c='Captain America';
            }
       
        }
    }
        
    }

}

For reference test class:

@isTest
public class TestOpportunityTeamUpdate {

    static testMethod void testStandardUseropp() {
        // Create a new user with the Standard User profile
    Profile standardProf = [select id from profile where name='Standard User'];
    User su = new User(alias = 'standt', email='standarduser@testorg.com',
      emailencodingkey='UTF-8',FirstName='opp', lastname='testing', languagelocalekey='en_US',
      localesidkey='en_US', profileid = standardProf.Id,
      timezonesidkey='America/Los_Angeles', username='sample@opptest.com');
      
    // Switch current user to Standard User
    System.runAs(su) {  
         Account acct = new Account(Name = 'Test Account');
        insert acct;
        opportunity opp=new opportunity (
            StageName = 'Prospecting',
            CloseDate = Date.today(),
            AccountId = acct.Id,
            Type='Existing Business',
            Demo_Status__c='No Show',
            Name = 'Test Opportunity Triggers'
           );
        insert opp;
        //System.debug('value :'+opp.Team_Name__c);
        //System.assertEquals(opp.Team_Name__c,'Captain America');
    }
}
}

 
Can we assign custom visualforce page to a record type of a standard object.I have two record types for standard object lead.My problem is how to create a custom visualforce for a recordtype. Because how to refer Leadstatus field based on a recordtype.

Thanks in advance.
I have a requirement to share lead records to a particular user when team = Bangalore team.

And team field is updating based on the owner of the lead record. Now I'm trying to create a test class for this requirement. But I'm facing an issue.

System.DmlException: Upsert failed. First exception on row 0 with id 00QN0000008KXuhMAG; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Trigger: execution of AfterUpdate

caused by: System.DmlException: Insert failed. First exception on row 0 with id 01oN0000009m7uUIAQ; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

Class.LeadSharing.BangaloreTeamShareUpdateordelete: line 47, column 1

Apex Test Class:

 
Static testmethod void testUpdateLeads()
    {
        List<Lead> leads = new List<Lead>{};
        Id queueID=[Select Queue.Id,Queue.name from QueueSObject where Queue.Name = 'Charlotte Leads' LIMIT 1].Queue.ID;
        Id userid=[Select id,name from user where name='Pavan Kumar' Limit 1].Id;
        for(Integer i = 0; i < 20; i++) 
        {
            Lead a = new Lead(lastName='TestCavalry'+ i,RecordTypeId ='0126F0000016MZP',
                              Company ='Azuga Cavalry'+ i,Status='New',Account_Category_new__c='Prospect',
                              Account_Category__c='Regular',Lead_Category__c='Sales',Lead_Type__c='Association List',
                              Lead_Source__c='NEFBA',LGS_Owner_new__c='Cavalry Test',ownerid=queueID);
            leads.add(a);
        }
        test.startTest();
        // Insert the Account records that cause the trigger to execute.
        insert leads;
        // Stop the test, this changes limit context back to test from trigger.
        test.stopTest();
        // assert that 0 shares exist
        List<LeadShare> shares = [select id from LeadShare where 
                                     LeadId IN :Leads and RowCause = 'Manual'];
        System.assertEquals(shares.size(),0);
        for(Lead leadidss:leads)
        {
            leadidss.ownerid=userid;
        }
        update leads;
        // assert that 20 shares were created
        shares = [select id from LeadShare where LeadId IN :leads and RowCause = 'Manual'];
        System.assertEquals(shares.size(),20);
        /*
        **for(Lead leadids:leads)
        {
            leadids.ownerid=QueueID;
        }**
        update leads;
        // assert that 0 shares were created
        shares = [select id from LeadShare where LeadId IN :leads and RowCause = 'Manual'];
        System.assertEquals(shares.size(),0);*/
    }

And line 47 would be.
 
for(Lead leadids:leads)
            {
                leadids.ownerid=QueueID;
            }

Apex Class:
 
public static void BangaloreTeamShareUpdateordelete(List<Lead> newleads,Map<Id,Lead> oldmapleads)
    {
        List<Id> Sharedeletionlist = new List<Id>();
        List<LeadShare> Shareinsertlist = new List<LeadShare>();
        for(Lead leadid:newleads)
        {
            if(oldmapleads.get(leadid.id).team__c == 'Bangalore Team' && 
               (leadid.Team__c <> 'Bangalore Team' || String.isBlank(leadid.Team__c)) )
            {
                Sharedeletionlist.add(leadid.id);
            }
            else if((oldmapleads.get(leadid.Id).team__c <> 'Bangalore Team' || String.isBlank(oldmapleads.get(leadid.id).team__c)) && 
                    leadid.Team__c == 'Bangalore Team')
            {
                leadshare leadshareid= new leadshare();
                leadshareid.LeadId=LeadId.Id;
                leadshareid.UserOrGroupId=userid;
                leadshareid.LeadAccessLevel='edit';
                Shareinsertlist.add(leadshareid);
            }
            if(Sharedeletionlist <> null && !Sharedeletionlist.isEmpty())
            {
                delete[Select id from leadshare where leadid IN :Sharedeletionlist AND RowCause='Manual'];
            }
            If(Shareinsertlist <> null && !Shareinsertlist.isEmpty())
            {
                insert Shareinsertlist;
            }
        }
    }

I tried multiple ways like disabling parallel apex test execution. And updating update DML statement to upsert.

Please guide me where I went wrong.
 
public class AuthCallout {
    public void basicAccessTokenGeneration() {
     HttpRequest req = new HttpRequest();
     req.setEndpoint('https://');
     req.setMethod('POST');

     // Specify the required username and password to access the endpoint
     // As well as the header and header information

     String username = '';
     String password = '';
     String vendor   = '';
     String businessunit ='';
     String application ='';

     Blob headerValue = Blob.valueOf(application + '@' + vendor + ':' + businessunit);
     String authorizationHeader = 'BASIC ' +
     EncodingUtil.base64Encode(headerValue);
     req.setHeader('Authorization', authorizationHeader);


    JSONGenerator gen = JSON.createGenerator(true);    

    gen.writeStartObject();      
    gen.writeStringField('grant_type ', 'password');
    gen.writeStringField('username', username);
    gen.writeStringField('password',password);
    gen.writeStringField('scope','');
    gen.writeEndObject();
    String jsonS = gen.getAsString();
    system.debug('DAta in '+str);
    system.debug('Data in gen'+jsonS);
    req.setBody(jsonS);
     // Create a new http object to send the request object
     // A response object is generated as a result of the request  

     Http http = new Http();
     HTTPResponse res = http.send(req);
     System.debug(res.getBody());
        System.debug(res.getStatusCode());
        System.debug(res.getBodyDocument());
   }
}

'm new to integration. I am going to generate an access token for the third-party application.
I tried to build following javascript request in sfdc.

But the response body is blank. I need to retrieve access token & other things to call specific endpoint in another class.
Please let me know where i did wrong

I am searlize JSON string also while sending the body

They gave same code request sample in java format like below.

Sample request
var result = {};
var application = "";
var vendor = "";
var businessunit = "";
var user = "";
var pass = "";
var authCode = window.btoa(application + "@" + vendor + ":" + businessunit);
$.ajax({
    "url": 'https://',
    "type": 'post',
    "contentType": 'application/json',
    "dataType": 'json',
    "headers": {
        'Authorization': 'basic ' + authCode
    },
    "data": JSON.stringify({
    "grant_type": 'password',
    "username": user,
    "password" : pass,
    "scope": 'AdminApi AgentApi AuthenticationApi PatronApi RealTimeApi'
    }),
    "success": function (resp) {
        result.access_token = resp.access_token;
        result.token_type = resp.token_type;
        result.resource_server_base_uri = resp.resource_server_base_uri;
        result.expires_in = resp.expires_in;
        result.refresh_token = resp.refresh_token;
        result.scope = resp.scope;
        result.refresh_token_server_uri = resp.refresh_token_server_uri;
    },
    "error": function (XMLHttpRequest, textStatus, errorThrown) {
        alert("Failed to retrieve token.\n" + XMLHttpRequest.status + ' ' 
            + XMLHttpRequest.statusText);
    }
});

My Apex

 
 am sending sample survey email to users whenever accounts meets particular criteria.

I created a apex class and iam accessing contacts and sending contact details to below SendEmail method.Now i am attaching a link within email template through HTML body but i dont want to send long link to the user.

Is there any way to hyperlink above link to small text or clickable image.

Like Below:
 
public Static void sendMail(Id accountdetails,String Emaildetails,Id Contactdetails,Id CaseId,String Customername,String Accountsname)
    {
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        List<String> sendTo = new List<String>();
        sendTo.add(Emaildetails);
        mail.setToAddresses(sendTo);
        mail.setReplyTo('pavank@azuga.com');
        mail.setSenderDisplayName('Azuga Telematics');
        mail.setsubject('Invitation to participate in survey');
        String body = 'Hi '+Customername+','+'<br/>'+'<br/>';
        body += 'Account Name:'+'<br/>'+'<br/>';
        body += Label.Churn_Site_Details+'&cId='+Contactdetails+'&caId='+CaseId;
        mail.setHtmlBody(body);
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
        inspectResults(results,accountdetails);
    }

 
Hi friends i got a requirement to summarize call duration.So,I created a custom field with Call Duration(Minutes).
IF((MOD(CallDurationInSeconds/60,1)*60) > 10, VALUE(TEXT(FLOOR( CallDurationInSeconds/60)) + "." + TEXT(FLOOR(MOD( CallDurationInSeconds/60,1)*60) )), VALUE(TEXT(FLOOR( CallDurationInSeconds/60)) + ".0" + TEXT(FLOOR(MOD( CallDurationInSeconds/60,1)*60) )) )

Now i am able to summarize but it's showing everything in minutes like for 1 hour 50 minutes.It's showing 150.Please i want like in hours and minutes format.
Got a requirement like to calculate average in account based on particular record type of case. My requirement is:

I have a field called ARP in account currency. I want to calculate overall average of ARP field in particular record type called customer order whether Case details either new or add-on.

So I'm trying write a trigger a trigger.

Everything is working fine in sandbox but in production when i update any old cases it's not updating accurately.If i do update in sandbox is working fine.

And for example there is case with above criteria like 18.55.But it updating 6.55.When i check from random accounts it  is calculating average with all cases to a respective account.

When i try to create any cases with new accounts it is working fine.Please help me guys to sort out.

trigger ForARPU on case (after insert,after update,after delete) 
   {
       if(Trigger.isAfter && trigger.isInsert || Trigger.isAfter && trigger.isUpdate) 
    {     
        //It will call a static method called ARPUInsert in ARPUCases class.
        ARPUCases.ARPUInsert(Trigger.New);

    }
}

Handler trigger

public static void ARPUInsert(List<Case>  CaseTriggers)
    {
        /** 
         * This method is to caluclate average of all ARPU amounts with case have customer order recordtype
         * as well as case details with either ADD-On (OR) New Subscription and update in related account
         * field called ARPU. 
         * This method will fire only when any case with record type called customer order is created as well updated. 
        */
        Id recordTypeId = [Select Id From RecordType Where DeveloperName = 'Customer_Order'].Id;
        List<Account> Accountstoupdate =new List<Account>();
        List<Case> CaseIDs = new List<Case>();
        for (Case s : CaseTriggers)
        {
            if(s.RecordTypeId == recordTypeId && (s.Case_Details__c =='New Subscription' || s.Case_Details__c =='Add On') ) 
            {
                    // Loop through and add caseId's to the list.
                    CaseIDs.add(s);
            }
        }
        /** @Var CaseAccountIds - to get accountId's of cases with list called CaseIDs */
        set<Id> CaseAccountIds = new set<Id>();
        for(Case c : [SELECT Id,ARPU__c,accountId FROM Case WHERE Id IN :CaseIDs])
        {
            // Loop through and add AccountId's to the list.
            CaseAccountIds.add(c.AccountId);
        }
        /** @Var Accountswithcases-to get account details to caluclate average */
        /** @Var results-to get average of particular account based on the cases */
        List<Account> Accountswithcases = [select Id,name,ARPU__c  from Account where id =:CaseAccountIds];
        Map<Id, AggregateResult> results = new Map<Id, AggregateResult>(
            [SELECT AccountId Id, AVG(ARPU__c) average FROM Case WHERE AccountId = :Accountswithcases GROUP BY AccountId]);
        For(account a1: Accountswithcases) 
        {
            if(results.get(a1.Id) != null) 
            {
                // Loop through aggregate results array and typecast the average of ARPU and update in account level.
                a1.ARPU__c = (Decimal)results.get(a1.Id).get('average');
                Accountstoupdate.add(a1);
            }
        }
        if(Accountstoupdate.size()>0) 
        {
            // DML statement to update all the accounts related with cases
            update Accountstoupdate;
        }
}

 
got a requirement like to calculate average in account based on particular record type of case. My requirement is:

I have a field called ARP in account currency. I want to calculate overall average of ARP field in particular record type called customer order whether Case details either new or add-on.

So I'm trying write a trigger a trigger.

Everything is working but after delete event is not working means.

Example when i create a case with ARPU will be 21.And if i delete the case it's still showing 21 in account level.Even i am trigger.old in trigger to handler class.


My trigger would be 

trigger ForARPU on case (after insert,after update,after delete) 
{  
    if(Trigger.isAfter && trigger.isInsert || Trigger.isAfter && trigger.isUpdate ) 
    {      
        //It will call a static method called ARPUInsert in ARPUCases class.
        ARPUCases.ARPUInsert(Trigger.New);
    
    }
    if(Trigger.isAfter && trigger.isDelete) 
    {     
        //It will call a static method called ARPUInsert in ARPUCases class.
        ARPUCases.ARPUDelete(Trigger.Old);
    
    }
}

Handler class would be My debug Logs

/**
 * This class is used to calculate average of Arpu in customer order record type
 * with cases details either Add-on or New subscription and update in Related Account field called ARPU.
 * This class is fire whenever record type called customer order case has been inserted or updated or deleted.
 * @author  Pavan Kumar
 * @since   2016-09-28 
*/
public class ARPUCases 
{
    /** @var recordTypeID - is to filter cases with particular record type */
    /** @var Accountstoupdate - is to update the particular accounts */
    /** @var CaseIDs - is to retrive all related case id's */
     
    public static Set<Account> accSet = new Set<Account>();
    
    public static void ARPUInsert(List<Case>  CaseTriggers)
    {
        /** 
         * This method is to caluclate average of all ARPU amounts with case have customer order recordtype
         * as well as case details with either ADD-On (OR) New Subscription and update in related account
         * field called ARPU. 
         * This method will fire only when any case with record type called customer order is created as well updated. 
        */
        
        if (Trigger.isInsert || Trigger.isUpdate) 
        {
            Id recordTypeId = [Select Id From RecordType Where DeveloperName = 'Customer_Order'].Id;
     List<Account> Accountstoupdate =new List<Account>();
     List<Case> CaseIDs = new List<Case>();
            for (Case s : CaseTriggers)
            {
                if(s.RecordTypeId == recordTypeId && s.Case_Details__c =='New Subscription' || s.Case_Details__c =='Add On' ) 
                {
                    // Loop through and add caseId's to the list.
                    CaseIDs.add(s);
                }
            }
            /** @Var CaseAccountIds - to get accountId's of cases with list called CaseIDs */
            set<Id> CaseAccountIds = new set<Id>();
            
            for(Case c : [SELECT Id,ARPU__c,accountId FROM Case WHERE Id IN :CaseIDs])
            {
                // Loop through and add AccountId's to the list.
                CaseAccountIds.add(c.AccountId);
            }
            /** @Var Accountswithcases-to get account details to caluclate average */
            /** @Var results-to get average of particular account based on the cases */
            List<Account> Accountswithcases = [select Id,name,ARPU__c  from Account where id =:CaseAccountIds];
            Map<Id, AggregateResult> results = new Map<Id, AggregateResult>(
                [SELECT AccountId Id, AVG(ARPU__c) average FROM Case WHERE AccountId = :Accountswithcases GROUP BY AccountId]);
            For(account a1: Accountswithcases) 
            {
                if(results.get(a1.Id) != null) 
                {
                    // Loop through aggregate results array and typecast the average of ARPU and update in account level.
                    a1.ARPU__c = (Decimal)results.get(a1.Id).get('average');
                    Accountstoupdate.add(a1);
                }
                
            }
            if(Accountstoupdate.size()>0) 
            {
                // DML statement to update all the accounts related with cases
                update Accountstoupdate;
            }
        }
    }
    public static void ARPUDelete(List<Case>  CaseTriggers) 
    {
        /** 
         * This method is to caluclate average of all ARPU amounts with case have customer order recordtype
         * as well as case details with either ADD-On (OR) New Subscription and update in related account
         * field called ARPU. 
         * This method will fire only when any case with record type called customer order is deleted. 
        */
        
        if (Trigger.isDelete)
        {
            Id recordTypeId = [Select Id From RecordType Where DeveloperName = 'Customer_Order'].Id;
     List<Account> Accountstoupdate =new List<Account>();
     List<Case> CaseIDs = new List<Case>();
            for (Case s : CaseTriggers)
            {
                if(s.RecordTypeId == recordTypeId && s.Case_Details__c =='New Subscription' || s.Case_Details__c =='Add On') 
                {
                    // Loop through and add caseId's to the list.
                    CaseIDs.add(s);
                }
            }
            System.debug('Data in  CaseIDs:'+ CaseIDs.size());
            System.debug('Data in  details CaseIDs:'+ CaseIDs);
            /** @Var CaseAccountIds - to get accountId's of cases with list called CaseIDs */
            set<Id> CaseAccountIds = new set<Id>();
            for(Case c : CaseTriggers)
            {
                 // Loop through and add AccountId's to the list.
                CaseAccountIds.add(c.AccountId);
            }
            System.debug('After Data in  CaseAccountIds:'+ CaseAccountIds.size());
            System.debug('After Data Details in  CaseAccountIds:'+ CaseAccountIds);
            /** @Var Accountswithcases-to get account details to caluclate average */
            /** @Var results-to get average of particular account based on the cases */
            List<Account> Accountswithcases = [select Id,name,ARPU__c  from Account where id =:CaseAccountIds];
            Map<Id, AggregateResult> results = new Map<Id, AggregateResult>(
                [SELECT AccountId Id, AVG(ARPU__c) average FROM Case WHERE AccountId = :Accountswithcases GROUP BY AccountId]);
            System.debug('Results:'+ results.size());
            System.debug('Data in Accountswithcases:'+ Accountswithcases.size());
            For(account a1: Accountswithcases) 
            {
                if(results.get(a1.Id) != null ) 
                {
                    // Loop through aggregate results array and typecast the average of ARPU and update in account level.
                    a1.ARPU__c = (Decimal)results.get(a1.Id).get('average');
                    Accountstoupdate.add(a1);
                }
            }
            System.debug('After Results:'+  Accountstoupdate.size());
            System.debug('Size of the Results:'+  Accountstoupdate);
            if(Accountstoupdate.size()>0) 
            {
                // DML statement to update all the accounts related with cases.
                update Accountstoupdate;
            } 
        }
    }
}

I am attaching my debug logs
Here is my Scenario :
In Lead Object there is a LastName field contains  the name of a patient . for example John Readmit , Jack Readmit 2 , Jason Readmit3.
Using formula field , I need to display 1 if suppose LastName contains John Readmit ,display 2 if LastName contains Jack Readmit 2 and display 3 if LastName contains Jason Readmit3.

Formula Field is Number Data Type

I have  used the formulae IF( CONTAINS( "Re-Admit:re admit:readmit:Readmit:Re admit:ReAdmit:Re Admit:Re-admit", LastName), IF( CONTAINS( " 2", LastName), 2, IF( CONTAINS( " 3", LastName), 3, 1 ) ), null)

but it shows blank value.

Please help,

Best,
Prakash
 
Hi friends i have a standard approval process in account.And in some scenarios the accounts submitted for approval multiple times.So, my requirement is to create a report for approvals in account.So, i create a custom report type but i need fields in account object.

So, for this requirement i need to add another child object to the account.And try to create a record when in goes for approval as specified below link

https://cherfeldman.blogspot.in/2014/01/potential-solution-for-reporting-on.html?showComment=1472502144116#c9027830380141607440

But,in my case is standard approval.User manually submits record for approval.So,I am confused to solve this issue.Please provide your suggestions for this requirement.
Hi Friends i got a requirement like whenever a case is created (Or) edited with specific criteria.I need to update specific field in opportunity.
So,for cases & opportunities have lookup relationship.But my requirement is single opportunities have multiple cases means we can use single opportunity in multiple cases.

I don't want to lose my data in opportunity if i can assign same opportunity in another case.

So,i came with process builder.

I do it like when a specific condition met.it updates a field in opportunity called

Churned units = Churned units+field in cases;

It's working only with one field.

For reference:

User-added image
I need to calculate days between two fields.

So I use daysBetween to complete when I try to do with two dates it's working fine.

But, when I try with list(or) map  it throws an error like:

Method does not exist or incorrect signature: [Date].daysBetween(List)

For reference my code:

public date closedates;
Public Long details;
List<Case> c=new List<case>();
List<Integer> Values=new List<Integer>();
//Integer Value=0;
List<Date> Churndate=new List<Date>();
List<Date> closedatesd=new List<Date>();
c=[Select Id,Date_Order_Received__c,accountId from case where RecordTypeId = '01290000000sF3L'];
System.debug('Data in Case '+c);
List<Id> accountIds= new List<Id>();
List<Account> accounts=new List<Account>();
List<Id> opps=new List<Id>();
List<Date> Oppsdate= new List<Date>();
for(Case cl:c) {
accountIds.add(cl.accountId);
//Churndate=cl.Date_Order_Received__c;
Churndate.add(cl.Date_Order_Received__c);
}
System.debug('Date value in '+churndate);
for(Account ao:[Select Id,name,(select Id,name,CloseDate from opportunities) from account where Id in:accountIds]) {
for(Opportunity opp : ao.opportunities) {
opps.add(opp.Id);
//details=closedates.daysBetween(Churndate);
**Values.add(opp.CloseDate.daysBetween(Churndate));**
//Other Operation you want to perform with every opportunity
}
}
Hi friends i am new to sfdc.I stuck in a problem called In case object we have 20 record types are avilable.We had created
some custom fields and we had using some fields in multiple record types.But my problem is i didn't create these recordtypes so
While i want to customize any one of these fields.I am trying to go and search each and every record rype layout.I am wasting lot of time while 
doing this everytime.Is there any way to know whether a picklist avilable in how many layouts or recordtypes.Please help me.
Can we assign custom visualforce page to a record type of a standard object.I have two record types for standard object lead.My problem is how to create a custom visualforce for a recordtype. Because how to refer Leadstatus field based on a recordtype.

Thanks in advance.