• Lee Sin
  • NEWBIE
  • 80 Points
  • Member since 2014
  • Certified Salesforce Developer

  • Chatter
    Feed
  • 0
    Best Answers
  • 4
    Likes Received
  • 0
    Likes Given
  • 26
    Questions
  • 14
    Replies
Hi,
I have a multiselect picklist which is displayed on a VF page using <apex:inputfield>
It worked well until I added&edited the field values. 
The options in the VF page's multiselect field stay the same(no new options added to the picklist)

How can I fix this?
My Controller:
global class AR_RepWorkingReport {
        //public Map<ID,User> reps;
        //
        //
        //DeclinedLeads: Invoice Status='Lead Refunded'
        //AcceptedLeads: Invoice Status='Lead Sold/Charged'
    public List<User> repsList;
    public String selectedRep{get;set;}
    public String startdate{get;set;}
    public String enddate{get;set;}
    public repstats statistics{get;set;}
    public List<clients> clientscount{get;set;}
    public List<PieWedgeData> ActivitiesPieData{get;set;}
    public List<PieWedgeData> ClientsPieData{get;set;}
    public boolean renderPie{get;set;}
    public AR_RepWorkingReport()
    {
        repsList=[select ID,Name from User where isActive=true and type_rep__c in ('Junior','Senior') order by Name ];
        statistics=new repstats();
        clientscount =new  List<clients>();  
        ActivitiesPieData=new List<PieWedgeData>();
        ClientsPieData=new List<PieWedgeData>();
        renderPie=false;
    }
    public List<PieWedgeData> getAcPieData()
    {
        return ActivitiesPieData;
    }
    public List<PieWedgeData> getclPieData()
    {
        return ClientsPieData;
    }
    public class PieWedgeData {
        public String name { get; set; }
        public Integer data { get; set; }
        public PieWedgeData(String name, Integer data) {
            this.name = name;
            this.data = data;
        }
    }
     public void getClientsPieData() {
        ClientsPieData = new List<PieWedgeData>();
        //List<PieWedgeData> clientsPie = new List<PieWedgeData>();
                For(clients c : clientscount)
        {
            if(Integer.valueOf(c.count)!=0){
                String chartclientName=c.Name==null?'None':C.name;
                ClientsPieData.add(new PieWedgeData(chartclientName, Integer.valueOf(c.count)));}
        }
    } 
    
    
    public void getActivitiesPieData() {
        ActivitiesPieData = new List<PieWedgeData>();
        //List<PieWedgeData> clientsPie = new List<PieWedgeData>();
        if(Integer.valueOf(statistics.voiceMail)!=0){
        ActivitiesPieData.add(new PieWedgeData('Voice Mail', Integer.valueOf(statistics.voiceMail)));
        }
        if(Integer.valueOf(statistics.ConversationCSuite)!=0){
        ActivitiesPieData.add(new PieWedgeData('Conversation with C Suite', Integer.valueOf(statistics.ConversationCSuite)));
        }
        if(Integer.valueOf(statistics.ConversationHR)!=0){
        ActivitiesPieData.add(new PieWedgeData('Conversation with HR', Integer.valueOf(statistics.ConversationHR)));
        }
        if(Integer.valueOf(statistics.ConversationOther)!=0){
        ActivitiesPieData.add(new PieWedgeData('Conversation - Other', Integer.valueOf(statistics.ConversationOther)));
        }
        if(Integer.valueOf(statistics.NML)!=0){
        ActivitiesPieData.add(new PieWedgeData('No Message Left', Integer.valueOf(statistics.NML)));
        }
        if(Integer.valueOf(statistics.FollowUpReminder)!=0){
        ActivitiesPieData.add(new PieWedgeData('Follow Up Reminder', Integer.valueOf(statistics.FollowUpReminder)));
        }
        if(Integer.valueOf(statistics.AcceptedLeads)!=0){
         ActivitiesPieData.add(new PieWedgeData('Accepted Leads', Integer.valueOf(statistics.AcceptedLeads)));
        }
        if(Integer.valueOf(statistics.DeclinedLeads)!=0){
         ActivitiesPieData.add(new PieWedgeData('Declined Leads', Integer.valueOf(statistics.DeclinedLeads)));
        }
        if(Integer.valueOf(statistics.RFI)!=0){
         ActivitiesPieData.add(new PieWedgeData('RFI', Integer.valueOf(statistics.RFI)));
        }
    } 
    /*
    public void getActivitiesPieData() {
        ActivitiesPieData = new List<PieWedgeData>();
        //List<PieWedgeData> clientsPie = new List<PieWedgeData>();
        ActivitiesPieData.add(new PieWedgeData('Voice Mail', 1));
        ActivitiesPieData.add(new PieWedgeData('Conversation with C Suite',2));
        ActivitiesPieData.add(new PieWedgeData('Conversation with HR', 3));
        ActivitiesPieData.add(new PieWedgeData('Conversation - Other',4));
        ActivitiesPieData.add(new PieWedgeData('No Message Left',5));
        ActivitiesPieData.add(new PieWedgeData('Follow Up Reminder', 6));
         ActivitiesPieData.add(new PieWedgeData('Accepted Leads', 7));
         ActivitiesPieData.add(new PieWedgeData('Declined Leads', 8));
         ActivitiesPieData.add(new PieWedgeData('RFI', 9));
    } */
    
    
    
    public void fetchRepBehaviors()
    {
        
        statistics=new repstats(); 
        clientscount =new  List<clients>();
        Map<String,integer> clientsmp=new Map<String,integer>();
        if(startdate!=null&&enddate!=null&&selectedRep!=null){
            Date statsstart=date.parse(startdate);
            Date statsend=date.parse(enddate);
            
            List<Task> repTasks=[select CallType__c,Contact_Type__c,whatId from Task where OwnerId=:selectedRep and createddate>=:statsstart and createddate<=:statsend];
            //IDs of Prospects
            List<ID> whatids=new LIst<ID>();
            List<Opportunity> repopps=[select Opportunity_Type__c,Opportunity_stage__c,Invoice_Status__c from Opportunity where (OwnerId=:selectedRep or Lead_sharing__c=:selectedRep) and createddate>=:statsstart and createddate<=:statsend];
           
            statistics.totalActivities=repTasks.size();
            System.debug('Number of Tasks: '+repTasks.size());
            for(Task t : repTasks)
            {
                if(t.CallType__c=='Conversation'){
                    if(t.Contact_Type__c=='Other'){statistics.ConversationOther++;}
                    else if(t.Contact_Type__c=='HR'){statistics.ConversationHR++;}
                    else if(t.Contact_Type__c=='C-Suite'){statistics.ConversationCSuite++;}
                }
                else if(t.CallType__c=='Left Voicemail'){
                    statistics.voiceMail++;
                }
                else if(t.CallType__c=='NML'){
                    statistics.NML++;
                }
                else if(t.CallType__c=='Follow up reminder'){
                    statistics.FollowUpReminder++;
                }
                whatids.add(t.whatid);
            }
            List<Account> prospects=[select Name,client_territories__c from Account where ID in :whatids];
            For(Account a: prospects)
            {
                if(clientsmp.containsKey(a.client_territories__c)){
                    Integer num=clientsmp.get(a.client_territories__c)+1;
                    clientsmp.put(a.client_territories__c, num);
                }
                else {
                    clientsmp.put(a.client_territories__c, 1);
                }
            }            
            For(String acctname : clientsmp.keySet()){
                clients c=new clients();
                c.count=clientsmp.get(acctname);
                c.name=acctname;
                clientscount.add(c);
            }
            
            For(Opportunity o : repopps){
                if(o.Opportunity_Type__c=='RFI'){
                    statistics.RFI++;
                }
                else if(o.Opportunity_Type__c=='Lead'){
                    if(o.Invoice_Status__c=='Lead Sold/Charged'){
                        statistics.AcceptedLeads++;
                    }
                    else if(o.Invoice_Status__c=='Lead Refunded'){
                        statistics.DeclinedLeads++;
                    }
                }
            }
            
        }
        renderPie=true;
        getActivitiesPieData();
        System.debug(ActivitiesPieData);
        getClientsPieData();
        System.debug(ClientsPieData);
    }
    

    
    //get the reps' names for the dropdown list
    public List<SelectOption> getReps(){
        List<SelectOption> options=new List<SelectOption>();
        for(User u : repsList){
            options.add(new SelectOption(u.id,u.name));
        }
        return options;
    }
    
    public class repstats
    {
        public repstats()
        {
            totalActivities=0;voiceMail=0;ConversationCSuite=0;ConversationHR=0;ConversationOther=0;AcceptedLeads=0;
            RFI=0;NML=0;FollowUpReminder=0;DeclinedLeads=0;
        }
        public integer totalActivities{get;set;}
        public integer voiceMail{get;set;}
        public integer ConversationCSuite{get;set;}
        public integer ConversationHR{get;set;}
        public integer ConversationOther{get;set;}
        public integer AcceptedLeads{get;set;}
        public integer RFI{get;set;}
        public integer NML{get;set;}
        public integer FollowUpReminder{get;set;}
        public integer DeclinedLeads{get;set;}
        
    }
    public class clients{
        public String Name{get;set;}
        public integer count{get;set;}
        public String ID{get;set;}        
    }
    
    
    
}

My VF Page:
<apex:page controller="AR_RepWorkingReport" showHeader="false" sidebar="false" standardStylesheets="false" docType="html-5.0">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script>
    var startdate,enddate;
    $(document).ready(function(){
        $("#arstart").datepicker({
        onSelect:function(dateText,inst){
            startdate=$(this).val();
            if(typeof enddate!=='undefined'){
                callActionMethod();
            }
        }}); 
        $("#arend").datepicker({
        onSelect:function(dateText,inst){
            enddate=$(this).val();
            if(typeof startdate!=='undefined'){
                callActionMethod();
            }
        }});    
    });
</script>
<script>
    function callActionMethod()
    {
        echo(startdate,enddate);
    }
</script>

<style type="text/css">
.pointer
{
    cursor:pointer;
    border:1px solid #ccc;
    padding: 5px;
}
</style>

</head>
<body>
    <div class="container">
        <div class="row well">
        <apex:form >  
            <div class="col-sm-2">         
                <apex:selectList value="{!selectedRep}" styleClass="form-control" size="1">           
                    <apex:selectOptions value="{!Reps}"></apex:selectOptions>
                    <apex:actionSupport event="onchange" reRender="resultPanel" action="{!fetchRepBehaviors}" status="myStatus"/>
                </apex:selectList>           
            </div>       
            <div style="float:left;">From:</div>
            <div class="col-sm-2 form-search">                        
                <input id="arstart"/>
            </div>
            <div style="float:left;">To:</div>
            <div class="col-sm-2">
                <input id="arend" />
            </div> 
         <apex:actionfunction name="echo" action="{!fetchRepBehaviors}" reRender="resultPanel" status="myStatus">
            <apex:param name="startdate" assignTo="{!startdate}" value=""/>
            <apex:param name="enddate" assignTo="{!enddate}" value=""/>    
        </apex:actionFunction>
        </apex:form>  
    </div>
</div>
<apex:outputPanel id="resultPanel">
        <apex:actionstatus startText="Requesting..." stopText="" id="myStatus" styleclass="hassuccess"/>
    <div class="container">
        <div class="row">
            <div class="col-md-3">    
                <table class="table  table-hover">
                    <tr>
                    <td style="color:orange"><apex:outputLabel value="Activity Type"/></td>
                    <td style="color:orange"><apex:outputLabel value="Count"/></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Voice Mail"/></td>
                    <td><apex:outputText value="{!statistics.voiceMail}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Conversation with C Suite"/></td>
                    <td><apex:outputText value="{!statistics.ConversationCSuite}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Conversation with HR"/></td>
                    <td><apex:outputText value="{!statistics.ConversationHR}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Conversation - Other"/></td>
                    <td><apex:outputText value="{!statistics.ConversationOther}"></apex:outputText></td>
                    </tr>                
                    <tr>
                    <td><apex:outputLabel value="No Message Left"/></td>
                    <td><apex:outputText value="{!statistics.NML}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Follow Up Reminder"/></td>    
                    <td><apex:outputText value="{!statistics.FollowUpReminder}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><b><apex:outputLabel value="Total Activities" style="color:red;"/></b></td>    
                    <td><apex:outputText value="{!statistics.totalActivities}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Accepted Leads"/></td>
                    <td><apex:outputText value="{!statistics.AcceptedLeads}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Declined Leads"/></td>
                    <td><apex:outputText value="{!statistics.DeclinedLeads}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="RFI"/></td>
                    <td><apex:outputText value="{!statistics.RFI}"></apex:outputText></td>
                    </tr>
                </table>    
            </div>
  
        <div class="col-md-5">    
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th style="color:orange">Client Territory</th>
                        <th style="color:orange">Count</th>
                    </tr>
                </thead>
                <tbody>
                    <apex:repeat value="{!clientscount}" var="List">
                    <tr>
                        <td><apex:outputLabel value="{!List.Name}"></apex:outputLabel></td>
                          <td><apex:outputLabel value="{!List.count}"></apex:outputLabel></td>
                    </tr>
                    </apex:repeat>
                </tbody>
            </table>
         </div>  
       </div>
    </div>
    
<div>
            <apex:chart height="350" width="450" data="{!AcPieData}" rendered="{!renderPie}">
                <apex:pieSeries dataField="data" labelField="name"/>
                <apex:legend position="right"/>
            </apex:chart>  
            </div>
            <div>

</div>
</apex:outputPanel>
         <div class="navbar navbar-default navbar-fixed-bottom">
    <div class="container">
        <p class="navbar-text pull-left">Site Built by Jack Wang, Dallas TX, 2014</p>
        <a class="navbar-btn btn-info btn pull-right" href="mailto:jack.wang@accelerationretirement.com">Contact Me</a> 
    </div>  
    </div>



</body>
</html>
</apex:page>

The JS Debug Log:
User-added image

User-added image
 
User-added image
I put this char component in a outputpanel.
I am using bootstrap in the VF page.  
I set the standardstylesheet to be "false" and doctype to be "html-5.0"

 
public List<PieWedgeData> ActivitiesPieData{get;set;}
public void getActivitiesPieData() {
        ActivitiesPieData = new List<PieWedgeData>();
        //List<PieWedgeData> clientsPie = new List<PieWedgeData>();
        ActivitiesPieData.add(new PieWedgeData('Voice Mail', statistics.voiceMail));
        ActivitiesPieData.add(new PieWedgeData('Conversation with C Suite', statistics.ConversationCSuite));
        ActivitiesPieData.add(new PieWedgeData('Conversation with HR', statistics.ConversationHR));
        ActivitiesPieData.add(new PieWedgeData('Conversation - Other', statistics.ConversationOther));
        ActivitiesPieData.add(new PieWedgeData('No Message Left', statistics.NML));
        ActivitiesPieData.add(new PieWedgeData('Follow Up Reminder', statistics.FollowUpReminder));
         ActivitiesPieData.add(new PieWedgeData('Accepted Leads', statistics.AcceptedLeads));
         ActivitiesPieData.add(new PieWedgeData('Declined Leads', statistics.DeclinedLeads));
         ActivitiesPieData.add(new PieWedgeData('RFI', statistics.RFI));
    } 



<apex:chart height="350" width="450" data="{!ActivitiesPieData}">
                <apex:pieSeries dataField="data" labelField="name"/>
                <apex:legend position="right"/>
            </apex:chart>





 
I want to programmatically change the Criteria based sharing rule on Account.

After read the material, I found nothing.
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_bulk_sharing_creating_with_apex.htm

I want to change the criteria through apex or enable/disable a sharing rule through apex.

My scenario:
I want to open certain accounts to users for them to work on. When a goal is reached, the manager can click a button to hide the accounts from the users. And when the next month comes, the manager clicks a button to enable the sharing rule.


 
I am trying to query the standard 'Description' field of Opportunity and put it into an HTML table.(I am writing HTML email not VF page)
This field is a long text area field.

In the standard page layout, the text is separated by several line breaks.
But in my apex code, when I store it in a string, I can not find  '\r\n' in the string. 

Any ideas?
Thanks in advance.
Hi, 
I am created a datatable on VF page which displays the subjects of a custom object instances.
I want to display the body of the instance  on a small pop up window when the mouse hover on a specific row. 

What are the basic steps to realize this or can I get some sample code on this ?

Thanks in advance!
If I have an operation that runs on page refresh or load, where should I put that logic?

Should I put it in the controller's constructor or a method and add an 'action' property in the <apex:page action={!***}></apex:page>

Is there any difference?
<apex:page showHeader="false" sidebar="false">
<script src="../../soap/ajax/32.0/connection.js" type="text/javascript"></script>
<script>
function setupPage(){
var content='';
result = sforce.connection.query("Select Name, Id from User");
records = result.getArray("records");
for (var i=0; i< records.length; i++) {
var record = records[i];
log(record.Name + " -- " + record.Id);
}
</script>
<body onload="setupPage();">
<div id="output"></div>
</body>
</apex:page>

I have 2 questions:
1. I want to add a break point to the scripts but I couldn't find the scripts in the chrome debug window. What's the name of the scripts that I wrote?
2. where can i see the logs specified here:
"log(record.Name + " -- " + record.Id);"


Hi, I am using the Sample Code of Salesforce .NET toolkit. 
I am able to get the query result from a Console Application. However, after I moved the code to MVC application, it gives me this error.
"The format of value 'https://login.salesforce.com/services/oauth2/token/v30.0' is invalid."

Here's the code:
public static async Task<List<AdvisorMapInfo>> getAdvisorsAsync()
        {
            var auth = new AuthenticationClient();
            //Authenticate with Salesforce
            var url = IsSandboxUser.Equals("true", StringComparison.CurrentCultureIgnoreCase)
                ? "https://test.salesforce.com/services/oauth2/token"
                : "https://login.salesforce.com/services/oauth2/token";

            await auth.UsernamePasswordAsync(ConsumerKey, ConsumerSecret, Username, Password, url);           
            var client = new ForceClient(auth.InstanceUrl, auth.AccessToken, auth.ApiVersion);
            const string qry = "SELECT Name,Primary_Contact__c,Asset_Range_Lower__c,Asset_Range_Upper__c,BillingAddress FROM Account WHERE (Account_Type__c='Advisor' or Account_Type__c='provider')";
            var accts = new List<AdvisorMapInfo>();
            var results = await client.QueryAsync<AdvisorMapInfo>(qry);
            var totalSize = results.totalSize;
            accts.AddRange(results.records);
            var nextRecordsUrl = results.nextRecordsUrl;
            if (!String.IsNullOrEmpty(nextRecordsUrl))
            {
                while (true)
                {
                    var continuationResults = await client.QueryContinuationAsync<AdvisorMapInfo>(nextRecordsUrl);
                    totalSize = continuationResults.totalSize;
                    accts.AddRange(continuationResults.records);
                    if (string.IsNullOrEmpty(continuationResults.nextRecordsUrl)) break;
                    nextRecordsUrl = continuationResults.nextRecordsUrl;
                }
            }
            return accts;
            
        }


    }

public ActionResult AdvisorsMap()
        {
            List<AdvisorMapInfo> result = AdvisorsMapBL.getAdvisorsAsync().Result;
            return View(result);            
        }


 
[SELECT Contact.FirstName, Contact.Account.Name from Contact order by Contact.Account.Name  limit 1000]

Why is this query not working
I want to order the result of a query and process the result following the order. So I can control the heap size.
If my query is   "select id,Accountid,email from Contact order by Accountid",
When the system split the query result to batches, are the batches split in order or randomly?


 
I am trying to find the duplicate emails under same account.
I have limited soql abilities so I didn't use "group" in my query at the time.
i wrote a batch apex class to process all the contacts to find the duplicate pairs but I got error "Batch Apex Error: Batchable Instance Is Too Big"
I tried the following:
1. Change the batch size to be 150 or 180.  
2. Searched this error in this forum, people encountered this when they were importing csv files or when they mistakenly added "Database.Stateful" keyword.

I don't quite understand the heap limit here, for each batch, what is the limit?  How can I know which part of my code comsumes most of the heap so I can try to fix my code?
Thank you!

 
global class ContactsCleaning implements Database.Batchable<sObject>,Database.Stateful{
    //query: select id,Accountid,email from Contact where email !=null and email!='\'\'' and accountid!=null and accountid!='\'\''
    public Map<AccountEmail,List<Contact>> duplicatePairs=new Map<AccountEmail,List<Contact>>();
    public integer totalemail=0;
    public integer totalcontact=0;
    global final String query;
    global ContactsCleaning(String q){
        query=q;
    }    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {
        for(Contact c : scope)
        {                        
                //check if email&account pair exists
                AccountEmail ae=new AccountEmail(c.AccountId,c.Email);
                if(duplicatePairs.containsKey(ae))
                {
                    duplicatePairs.get(ae).add(c);                  
                }
                else
                {                    
                    List<Contact> cl=new List<Contact>();
                    cl.add(c);
                    duplicatePairs.put(ae, cl);                    
                }            
        }                
    }    
    global void finish(Database.BatchableContext BC)
    {
        Document d=new Document();
        d.Name='Duplicate Emails';
        d.folderid = UserInfo.getUserId();
        String content='';
        for(AccountEmail ae : duplicatePairs.keySet())
        {
            if(duplicatePairs.get(ae).size()<=1)
            {
                duplicatePairs.remove(ae);
            }
            else
            {
                List<Contact> ls=duplicatePairs.get(ae);
                content=content+'Account: '+ae.AccountID+'   '+'Email:   '+ae.Email+'   ';
                Integer i=1;
                for(Contact c : ls)
                {
                    content=content+i+'   '+'ContactId:  '+c.Id+'   ';
                    i++;
                }
                content+='\n';
            }
        }
        d.Body=Blob.valueOf(content);
        d.ContentType='text/plain';
        d.Type='txt';
        insert d;
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'jack.wang@accelerationretirement.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Duplicate Email Stats');
        mail.setPlainTextBody('Total Contacts:   '+totalcontact+'\n'+'Total Emails:   '+totalemail+'\n'+'Deplicate Pairs:   '+duplicatePairs.size());
        mail.setHtmlBody('<div>Total Contacts:   '+totalcontact+'</div>'+'Total Emails:   '+totalemail+'</div><div>Deplicate Pairs:   '+duplicatePairs.size()+'</div>');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });                                
    }    
}
//This class is the key to dedup email of Contact
public class AccountEmail {
    public String AccountID;
    public String Email;
    public AccountEmail()
    {
    }
    public AccountEmail(String acctid,String e)
    {
        AccountID=acctid;
        Email=e;
    }
    public Boolean equals(Object obj) {
        if (obj instanceof AccountEmail) {
            AccountEmail p = (AccountEmail)obj;
            return ((AccountID==p.AccountID) && (Email==p.Email));
        }
        return false;
    }

    public Integer hashCode() {
        return (31 * AccountID.hashCode()) ^ (Email.hashCode());
    }

}






 
I am doing Email-Campaigns for all of our clients.
Basicly, the clients are 'Parent' Accounts in SF and we are going to do a mail-merge to all the children Accounts(Contacts of those accounts)  of those clients respectively.
I have some requirements here:

1. We want to send mass emails on-behalf of our client so the sender should be our client's email.
2. We want to track the emails(e.g. how many are opened)
3. We have 50+ clients so we don't want to create SF login for each of them.

How am I able to do this? 
Through API? How can I track email through API?
 
I have two address fields on Account. 
I need to create a new field to store the driving distance of these two fields.
Right now, I am using Google Map and VF page to display the distance of the two addresses but the distance is calculated every time the user opens the record.

There are two situatations:
a1. the two addresses are static.
a2. the two addresses are prone to be changed.

b1. the distance is the direct distance
b2. the distance is the driving distance

What approaches am I able to always have a field showing the up to date distance of the two fields?




I'm a graduate student of Computer Science gradating this December. 
Have 1 year experience with Salesforce, before that have work experience with .net.
Wrote VF pages, triggers, Batch apex, scheduled apex, workflows, approval processes.
Taking 401 certification in a month.

If you know any open positions please contact me.

I need to process a shared Map type variable after all batched are executed.
How can I use an if statement to judge this?
  • September 25, 2014
  • Like
  • 0

1. I wrote a test class for the batch apex class.  The result is not as expected so I want to watch the variables in Batch Class.

global class AR_Creating75DummyNML implements Database.Batchable<sObject>{

global final String query;
global AR_Creating75DummyNML(String q)
    {
        query=q;
    } 
global Database.QueryLocator start(Database.BatchableContext BC)
    {        
        return Database.getQueryLocator(query);        
    }

global void execute(Database.BatchableContext BC, List<Account> scope)
    {
        System.debug(scope.size());


      .........
}
}

I want to watch the size of the List passed from start method to execute method.
But when I run the test class, it only shows the variables in the test method. How can I watch the variable scope?

2.  Am I using System.abortJob correctly?
Test.startTest();
        AR_Creating75DummyNML c=new AR_Creating75DummyNML(query);
        ID batchID=Database.executeBatch(c);
        System.abortJob(batchID);
        Test.stopTest();
I got an error (No more than one executeBatch can be called from withink a testmethod.)  before I used System.abortJob.
So does this mean if the scope size is over 200, I have to use this System.abortJob(batchID)?


  • September 24, 2014
  • Like
  • 0
/*
 * **Created by Jack Wang 9.24.2014
*/
global class AR_Creating75DummyNML implements Database.Batchable<sObject>{
    
    static final Integer numofNML=75;
    global final String query;
    global AR_Creating75DummyNML(String q)
    {
        query=q;
    }
    
    public List<Task> createNML(List<ID> IDs)
    {
        integer size=IDs.size();
        List<integer> ints=new List<integer>();
        
        Integer numberDays = date.daysInMonth(Date.today().year(), Date.today().month());
        for(integer i=0;i<75;i++)
        {
            double k=Math.random()*size;
            ints.add(k.intValue());          
        }
        
        
        string userid=null;
        User[] users=[select id from User where name='Jeremy Young'];
        if(users.size()>0)
        {
            userid=users[0].id;
        }
        List<Task> tsks=new List<Task>();
        for(Integer i : ints)
        {
            double datek=Math.random()*numberDays;
            Task nml=new Task(ownerid=userid,CallType__c='NML',whatid=String.valueOf(IDs[i]),Subject='NML',
                              Status='Completed',Priority='Normal',ActivityDate=Date.today().tostartofMonth().addDays(datek.intValue()));
            tsks.add(nml);
        }
        return tsks;
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {        
        return Database.getQueryLocator(query);        
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope)
    {
        
        Map<String,List<ID>> territoryClientIDMap=new Map<String,List<ID>>();
        for(Account client : scope)
        {
            if(territoryClientIDMap.containsKey(client.client_territories__c))
            {
                territoryClientIDMap.get(client.client_territories__c).add(client.Id);
            }
            else
            {
                territoryClientIDMap.put(client.client_territories__c, new List<ID>());
                territoryClientIDMap.get(client.client_territories__c).add(client.Id);
            }
        }
        
        for(List<ID> clientIDS : territoryClientIDMap.values())
        {
            List<Task> tsks=createNML(clientIDS);
            insert tsks;
        }
        
        
    }
    
    global void finish(Database.BatchableContext BC)
    {
        
    }

}
@isTest
private class Test_AR_Creating75DummyNML {
    
    
    static testMethod void Test(){
        //create 10 advisors
        ////for each advisor create 100 clients
        //

        string userid=null;
        User[] users=[select id from User where name='Jeremy Young'];
        if(users.size()>0)
        {
            userid=users[0].id;
        }
        List<Account> advisors=new List<Account>();
    
        For(integer i=0;i<10;i++)
        {
            Account a=new Account(name='a'+String.valueOf(i),client_territories__c='a'+String.valueOf(i),account_type__c='provider',Monthly_Activity_Reporting__c=true,Account_Status__c='active');
            advisors.add(a);
        }
        insert advisors;
        
        For(integer j=0;j<advisors.size();j++)
        {
            List<Account> clients=new List<Account>();
            For(integer i=0;i<100;i++)
            {
                Account client=new Account(name=advisors[j].name+String.valueOf(i),client_territories__c=advisors[j].client_territories__c,account_type__c='prospect');
                clients.add(client);
            }
            insert clients;
        }
        
        
        List<Account> advisors1= [select client_territories__c from Account where
                                (account_type__c='provider' or account_type__c='advisor') 
                                 and Monthly_Activity_Reporting__c=true and Account_Status__c='active'];
        List<String> territories=new List<String>();
        List<String> advisorIDs=new List<String>();
        for(Account advisor : advisors1)
        {
            territories.add(advisor.client_territories__c);
            advisorIDs.add(advisor.id);
        }        
        //[select id,client_territories__c from Account where client_territories__c in :territories];
        string tempquery='Select id,client_territories__c from Account where client_territories__c in (';        
        for(String terr : territories)
        {
            tempquery+='\'';
            tempquery+=terr;
            tempquery+='\',';
        }
        tempquery=tempquery.substring(0, tempquery.length()-1);
        tempquery+=') and id not in (';
        for(String adid : advisorIDs)
        {
			tempquery+='\'';
            tempquery+=adid;
            tempquery+='\'';
            tempquery+=',';
        }
        string query=tempquery.substring(0, tempquery.length()-1);
        query+=')';
        
        Test.startTest();
        AR_Creating75DummyNML c=new AR_Creating75DummyNML(query);
        Database.executeBatch(c);
        Test.stopTest();
        
        List<Task> tsk=[select ownerid,CallType__c,Subject,
                              Status,Priority,ActivityDate from Task where createddate=TODAY and CallType__c='NML'
                       and ownerid= :userid and Status='Completed' and Priority='Normal'];
        
        //75 tasks for each advisor
        System.assertEquals(750, tsk.size());
        
        
	}

}

I tried to google this error, but I didn't get a satisfied answer.


  • September 24, 2014
  • Like
  • 0
I have two types of Account, advisor and client.
Each advisor has 3000 clients.  I want to get the 75 random clients and use their ids to create 75 tasks. 

//1 query 36 result rows
List<Account> advisors=[select id,account_type__c,client_territories__c from Account where account_type__c='advisor'];

for(Account a : advisors)
{
    //result rows too large, over 50000
    //For each advisor, create a list of its clients Account
    List<Account> clients=[select id from Account where client_territories__c=:a.client_territories__c];
    
    //Here I want to randomly pick 75 Account Ids and use that as whatid to create 75 Tasks
    
    //If I use the "Limit" Key word in the query, it will not generate random records right?

    
    
} 
  • September 22, 2014
  • Like
  • 0
User-added image

I am trying to build a report in apex and send an html email.
The report is basicly counting records number. But it has cross queries.
Can you look my code and comments and give me some advice?

Thank you!
  • September 20, 2014
  • Like
  • 0
My Controller:
global class AR_RepWorkingReport {
        //public Map<ID,User> reps;
        //
        //
        //DeclinedLeads: Invoice Status='Lead Refunded'
        //AcceptedLeads: Invoice Status='Lead Sold/Charged'
    public List<User> repsList;
    public String selectedRep{get;set;}
    public String startdate{get;set;}
    public String enddate{get;set;}
    public repstats statistics{get;set;}
    public List<clients> clientscount{get;set;}
    public List<PieWedgeData> ActivitiesPieData{get;set;}
    public List<PieWedgeData> ClientsPieData{get;set;}
    public boolean renderPie{get;set;}
    public AR_RepWorkingReport()
    {
        repsList=[select ID,Name from User where isActive=true and type_rep__c in ('Junior','Senior') order by Name ];
        statistics=new repstats();
        clientscount =new  List<clients>();  
        ActivitiesPieData=new List<PieWedgeData>();
        ClientsPieData=new List<PieWedgeData>();
        renderPie=false;
    }
    public List<PieWedgeData> getAcPieData()
    {
        return ActivitiesPieData;
    }
    public List<PieWedgeData> getclPieData()
    {
        return ClientsPieData;
    }
    public class PieWedgeData {
        public String name { get; set; }
        public Integer data { get; set; }
        public PieWedgeData(String name, Integer data) {
            this.name = name;
            this.data = data;
        }
    }
     public void getClientsPieData() {
        ClientsPieData = new List<PieWedgeData>();
        //List<PieWedgeData> clientsPie = new List<PieWedgeData>();
                For(clients c : clientscount)
        {
            if(Integer.valueOf(c.count)!=0){
                String chartclientName=c.Name==null?'None':C.name;
                ClientsPieData.add(new PieWedgeData(chartclientName, Integer.valueOf(c.count)));}
        }
    } 
    
    
    public void getActivitiesPieData() {
        ActivitiesPieData = new List<PieWedgeData>();
        //List<PieWedgeData> clientsPie = new List<PieWedgeData>();
        if(Integer.valueOf(statistics.voiceMail)!=0){
        ActivitiesPieData.add(new PieWedgeData('Voice Mail', Integer.valueOf(statistics.voiceMail)));
        }
        if(Integer.valueOf(statistics.ConversationCSuite)!=0){
        ActivitiesPieData.add(new PieWedgeData('Conversation with C Suite', Integer.valueOf(statistics.ConversationCSuite)));
        }
        if(Integer.valueOf(statistics.ConversationHR)!=0){
        ActivitiesPieData.add(new PieWedgeData('Conversation with HR', Integer.valueOf(statistics.ConversationHR)));
        }
        if(Integer.valueOf(statistics.ConversationOther)!=0){
        ActivitiesPieData.add(new PieWedgeData('Conversation - Other', Integer.valueOf(statistics.ConversationOther)));
        }
        if(Integer.valueOf(statistics.NML)!=0){
        ActivitiesPieData.add(new PieWedgeData('No Message Left', Integer.valueOf(statistics.NML)));
        }
        if(Integer.valueOf(statistics.FollowUpReminder)!=0){
        ActivitiesPieData.add(new PieWedgeData('Follow Up Reminder', Integer.valueOf(statistics.FollowUpReminder)));
        }
        if(Integer.valueOf(statistics.AcceptedLeads)!=0){
         ActivitiesPieData.add(new PieWedgeData('Accepted Leads', Integer.valueOf(statistics.AcceptedLeads)));
        }
        if(Integer.valueOf(statistics.DeclinedLeads)!=0){
         ActivitiesPieData.add(new PieWedgeData('Declined Leads', Integer.valueOf(statistics.DeclinedLeads)));
        }
        if(Integer.valueOf(statistics.RFI)!=0){
         ActivitiesPieData.add(new PieWedgeData('RFI', Integer.valueOf(statistics.RFI)));
        }
    } 
    /*
    public void getActivitiesPieData() {
        ActivitiesPieData = new List<PieWedgeData>();
        //List<PieWedgeData> clientsPie = new List<PieWedgeData>();
        ActivitiesPieData.add(new PieWedgeData('Voice Mail', 1));
        ActivitiesPieData.add(new PieWedgeData('Conversation with C Suite',2));
        ActivitiesPieData.add(new PieWedgeData('Conversation with HR', 3));
        ActivitiesPieData.add(new PieWedgeData('Conversation - Other',4));
        ActivitiesPieData.add(new PieWedgeData('No Message Left',5));
        ActivitiesPieData.add(new PieWedgeData('Follow Up Reminder', 6));
         ActivitiesPieData.add(new PieWedgeData('Accepted Leads', 7));
         ActivitiesPieData.add(new PieWedgeData('Declined Leads', 8));
         ActivitiesPieData.add(new PieWedgeData('RFI', 9));
    } */
    
    
    
    public void fetchRepBehaviors()
    {
        
        statistics=new repstats(); 
        clientscount =new  List<clients>();
        Map<String,integer> clientsmp=new Map<String,integer>();
        if(startdate!=null&&enddate!=null&&selectedRep!=null){
            Date statsstart=date.parse(startdate);
            Date statsend=date.parse(enddate);
            
            List<Task> repTasks=[select CallType__c,Contact_Type__c,whatId from Task where OwnerId=:selectedRep and createddate>=:statsstart and createddate<=:statsend];
            //IDs of Prospects
            List<ID> whatids=new LIst<ID>();
            List<Opportunity> repopps=[select Opportunity_Type__c,Opportunity_stage__c,Invoice_Status__c from Opportunity where (OwnerId=:selectedRep or Lead_sharing__c=:selectedRep) and createddate>=:statsstart and createddate<=:statsend];
           
            statistics.totalActivities=repTasks.size();
            System.debug('Number of Tasks: '+repTasks.size());
            for(Task t : repTasks)
            {
                if(t.CallType__c=='Conversation'){
                    if(t.Contact_Type__c=='Other'){statistics.ConversationOther++;}
                    else if(t.Contact_Type__c=='HR'){statistics.ConversationHR++;}
                    else if(t.Contact_Type__c=='C-Suite'){statistics.ConversationCSuite++;}
                }
                else if(t.CallType__c=='Left Voicemail'){
                    statistics.voiceMail++;
                }
                else if(t.CallType__c=='NML'){
                    statistics.NML++;
                }
                else if(t.CallType__c=='Follow up reminder'){
                    statistics.FollowUpReminder++;
                }
                whatids.add(t.whatid);
            }
            List<Account> prospects=[select Name,client_territories__c from Account where ID in :whatids];
            For(Account a: prospects)
            {
                if(clientsmp.containsKey(a.client_territories__c)){
                    Integer num=clientsmp.get(a.client_territories__c)+1;
                    clientsmp.put(a.client_territories__c, num);
                }
                else {
                    clientsmp.put(a.client_territories__c, 1);
                }
            }            
            For(String acctname : clientsmp.keySet()){
                clients c=new clients();
                c.count=clientsmp.get(acctname);
                c.name=acctname;
                clientscount.add(c);
            }
            
            For(Opportunity o : repopps){
                if(o.Opportunity_Type__c=='RFI'){
                    statistics.RFI++;
                }
                else if(o.Opportunity_Type__c=='Lead'){
                    if(o.Invoice_Status__c=='Lead Sold/Charged'){
                        statistics.AcceptedLeads++;
                    }
                    else if(o.Invoice_Status__c=='Lead Refunded'){
                        statistics.DeclinedLeads++;
                    }
                }
            }
            
        }
        renderPie=true;
        getActivitiesPieData();
        System.debug(ActivitiesPieData);
        getClientsPieData();
        System.debug(ClientsPieData);
    }
    

    
    //get the reps' names for the dropdown list
    public List<SelectOption> getReps(){
        List<SelectOption> options=new List<SelectOption>();
        for(User u : repsList){
            options.add(new SelectOption(u.id,u.name));
        }
        return options;
    }
    
    public class repstats
    {
        public repstats()
        {
            totalActivities=0;voiceMail=0;ConversationCSuite=0;ConversationHR=0;ConversationOther=0;AcceptedLeads=0;
            RFI=0;NML=0;FollowUpReminder=0;DeclinedLeads=0;
        }
        public integer totalActivities{get;set;}
        public integer voiceMail{get;set;}
        public integer ConversationCSuite{get;set;}
        public integer ConversationHR{get;set;}
        public integer ConversationOther{get;set;}
        public integer AcceptedLeads{get;set;}
        public integer RFI{get;set;}
        public integer NML{get;set;}
        public integer FollowUpReminder{get;set;}
        public integer DeclinedLeads{get;set;}
        
    }
    public class clients{
        public String Name{get;set;}
        public integer count{get;set;}
        public String ID{get;set;}        
    }
    
    
    
}

My VF Page:
<apex:page controller="AR_RepWorkingReport" showHeader="false" sidebar="false" standardStylesheets="false" docType="html-5.0">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script>
    var startdate,enddate;
    $(document).ready(function(){
        $("#arstart").datepicker({
        onSelect:function(dateText,inst){
            startdate=$(this).val();
            if(typeof enddate!=='undefined'){
                callActionMethod();
            }
        }}); 
        $("#arend").datepicker({
        onSelect:function(dateText,inst){
            enddate=$(this).val();
            if(typeof startdate!=='undefined'){
                callActionMethod();
            }
        }});    
    });
</script>
<script>
    function callActionMethod()
    {
        echo(startdate,enddate);
    }
</script>

<style type="text/css">
.pointer
{
    cursor:pointer;
    border:1px solid #ccc;
    padding: 5px;
}
</style>

</head>
<body>
    <div class="container">
        <div class="row well">
        <apex:form >  
            <div class="col-sm-2">         
                <apex:selectList value="{!selectedRep}" styleClass="form-control" size="1">           
                    <apex:selectOptions value="{!Reps}"></apex:selectOptions>
                    <apex:actionSupport event="onchange" reRender="resultPanel" action="{!fetchRepBehaviors}" status="myStatus"/>
                </apex:selectList>           
            </div>       
            <div style="float:left;">From:</div>
            <div class="col-sm-2 form-search">                        
                <input id="arstart"/>
            </div>
            <div style="float:left;">To:</div>
            <div class="col-sm-2">
                <input id="arend" />
            </div> 
         <apex:actionfunction name="echo" action="{!fetchRepBehaviors}" reRender="resultPanel" status="myStatus">
            <apex:param name="startdate" assignTo="{!startdate}" value=""/>
            <apex:param name="enddate" assignTo="{!enddate}" value=""/>    
        </apex:actionFunction>
        </apex:form>  
    </div>
</div>
<apex:outputPanel id="resultPanel">
        <apex:actionstatus startText="Requesting..." stopText="" id="myStatus" styleclass="hassuccess"/>
    <div class="container">
        <div class="row">
            <div class="col-md-3">    
                <table class="table  table-hover">
                    <tr>
                    <td style="color:orange"><apex:outputLabel value="Activity Type"/></td>
                    <td style="color:orange"><apex:outputLabel value="Count"/></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Voice Mail"/></td>
                    <td><apex:outputText value="{!statistics.voiceMail}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Conversation with C Suite"/></td>
                    <td><apex:outputText value="{!statistics.ConversationCSuite}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Conversation with HR"/></td>
                    <td><apex:outputText value="{!statistics.ConversationHR}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Conversation - Other"/></td>
                    <td><apex:outputText value="{!statistics.ConversationOther}"></apex:outputText></td>
                    </tr>                
                    <tr>
                    <td><apex:outputLabel value="No Message Left"/></td>
                    <td><apex:outputText value="{!statistics.NML}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Follow Up Reminder"/></td>    
                    <td><apex:outputText value="{!statistics.FollowUpReminder}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><b><apex:outputLabel value="Total Activities" style="color:red;"/></b></td>    
                    <td><apex:outputText value="{!statistics.totalActivities}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Accepted Leads"/></td>
                    <td><apex:outputText value="{!statistics.AcceptedLeads}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="Declined Leads"/></td>
                    <td><apex:outputText value="{!statistics.DeclinedLeads}"></apex:outputText></td>
                    </tr>
                    <tr>
                    <td><apex:outputLabel value="RFI"/></td>
                    <td><apex:outputText value="{!statistics.RFI}"></apex:outputText></td>
                    </tr>
                </table>    
            </div>
  
        <div class="col-md-5">    
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th style="color:orange">Client Territory</th>
                        <th style="color:orange">Count</th>
                    </tr>
                </thead>
                <tbody>
                    <apex:repeat value="{!clientscount}" var="List">
                    <tr>
                        <td><apex:outputLabel value="{!List.Name}"></apex:outputLabel></td>
                          <td><apex:outputLabel value="{!List.count}"></apex:outputLabel></td>
                    </tr>
                    </apex:repeat>
                </tbody>
            </table>
         </div>  
       </div>
    </div>
    
<div>
            <apex:chart height="350" width="450" data="{!AcPieData}" rendered="{!renderPie}">
                <apex:pieSeries dataField="data" labelField="name"/>
                <apex:legend position="right"/>
            </apex:chart>  
            </div>
            <div>

</div>
</apex:outputPanel>
         <div class="navbar navbar-default navbar-fixed-bottom">
    <div class="container">
        <p class="navbar-text pull-left">Site Built by Jack Wang, Dallas TX, 2014</p>
        <a class="navbar-btn btn-info btn pull-right" href="mailto:jack.wang@accelerationretirement.com">Contact Me</a> 
    </div>  
    </div>



</body>
</html>
</apex:page>

The JS Debug Log:
User-added image

User-added image
 
I am trying to query the standard 'Description' field of Opportunity and put it into an HTML table.(I am writing HTML email not VF page)
This field is a long text area field.

In the standard page layout, the text is separated by several line breaks.
But in my apex code, when I store it in a string, I can not find  '\r\n' in the string. 

Any ideas?
Thanks in advance.
I woud like to get the field name of the updated field in the after update trigger.

So how can I get the name in the trigger?
I am trying to pre-populate a picklist of 'calltype' by using URL hacking.

I have a Replated List of Contacts on Account Layout.

On the Related List, I have a custom button for creating new Activity.

The behavior of the botton is Exucute JavaScript.

I am using URLFOR method to create the url.

In the parameters list,  I am trying to add a default value for the picklist of filed 'calltype'.

I lookedup the ID of that picklist from pagesource to be '00NC0000005FPzF' but it shows error "missing field name" when I checked syntax.

So I tried other ways:

CF00NC0000005FPzF='NML',     no error but the picklist is not prepopulated
Task.00NC0000005FPzF='NML'   no error but the picklist is not prepopulated
NC0000005FPzF='NML',     no error but the picklist is not prepopulated

Why other fields all have names and ids  like 'tsk5' in the pagesource but only calltype  has name and id like '00NC0000005FPzF'?

here's my Js codes:

var recordIds = {!GETRECORDIDS($ObjectType.Contact)}
if(recordIds.length > 1) {
  alert("You must choose no more than one contact to record this voice mail.\n\nPlease check a box next to a contact and try again.")
}
else
{ var retURL = "/001";
  var links = document.getElementsByTagName("a");
  for( var ctr = 0; ctr < links.length; ctr++ ) {
  var href = links[ctr].href
  if( href != undefined && href.match(/\?(fcf|lsr)=/) ) {
    retURL =href
    break
  }
}
var finalHref = "{!URLFOR($Action.Activity.NewTask,null,[what_id=Account.Id,Activities.00NC0000005FPzF="NML",tsk5="NML",tsk12="Completed",tsk4=TEXT(MONTH(TODAY())) &"/" &TEXT(DAY(TODAY())) & "/"&TEXT(YEAR(TODAY()))],true)}"
finalHref = finalHref.replace(/retURL=[%\w\d]+&?/,'')
retURL = escape(retURL.replace(/https?:\/\/.*\.com/,""))
finalHref += (recordIds.length==1?("&who_id="+recordIds[0]):"")+"&retURL="+retURL
  window.top.location.href = finalHref
}

User-added image
I put this char component in a outputpanel.
I am using bootstrap in the VF page.  
I set the standardstylesheet to be "false" and doctype to be "html-5.0"

 
public List<PieWedgeData> ActivitiesPieData{get;set;}
public void getActivitiesPieData() {
        ActivitiesPieData = new List<PieWedgeData>();
        //List<PieWedgeData> clientsPie = new List<PieWedgeData>();
        ActivitiesPieData.add(new PieWedgeData('Voice Mail', statistics.voiceMail));
        ActivitiesPieData.add(new PieWedgeData('Conversation with C Suite', statistics.ConversationCSuite));
        ActivitiesPieData.add(new PieWedgeData('Conversation with HR', statistics.ConversationHR));
        ActivitiesPieData.add(new PieWedgeData('Conversation - Other', statistics.ConversationOther));
        ActivitiesPieData.add(new PieWedgeData('No Message Left', statistics.NML));
        ActivitiesPieData.add(new PieWedgeData('Follow Up Reminder', statistics.FollowUpReminder));
         ActivitiesPieData.add(new PieWedgeData('Accepted Leads', statistics.AcceptedLeads));
         ActivitiesPieData.add(new PieWedgeData('Declined Leads', statistics.DeclinedLeads));
         ActivitiesPieData.add(new PieWedgeData('RFI', statistics.RFI));
    } 



<apex:chart height="350" width="450" data="{!ActivitiesPieData}">
                <apex:pieSeries dataField="data" labelField="name"/>
                <apex:legend position="right"/>
            </apex:chart>





 
I have created my first trigger and tested it. I transfered it to production with change sets. when I validated it in production I got the following error
Your organization's code coverage is 58%. You need at least 75% coverage to complete this deployment. Also, the following triggers have 0% code coverage. Each trigger must have at least 1% code coverage.
I am the new admin of my org and know nothing about the other classes. In addition the classes that are giving the errors seem to be test classes that were never run. 
is there anyway to override this, since my trigger has enough coverage?
Hi, 
I am created a datatable on VF page which displays the subjects of a custom object instances.
I want to display the body of the instance  on a small pop up window when the mouse hover on a specific row. 

What are the basic steps to realize this or can I get some sample code on this ?

Thanks in advance!
<apex:page showHeader="false" sidebar="false">
<script src="../../soap/ajax/32.0/connection.js" type="text/javascript"></script>
<script>
function setupPage(){
var content='';
result = sforce.connection.query("Select Name, Id from User");
records = result.getArray("records");
for (var i=0; i< records.length; i++) {
var record = records[i];
log(record.Name + " -- " + record.Id);
}
</script>
<body onload="setupPage();">
<div id="output"></div>
</body>
</apex:page>

I have 2 questions:
1. I want to add a break point to the scripts but I couldn't find the scripts in the chrome debug window. What's the name of the scripts that I wrote?
2. where can i see the logs specified here:
"log(record.Name + " -- " + record.Id);"


I am trying to find the duplicate emails under same account.
I have limited soql abilities so I didn't use "group" in my query at the time.
i wrote a batch apex class to process all the contacts to find the duplicate pairs but I got error "Batch Apex Error: Batchable Instance Is Too Big"
I tried the following:
1. Change the batch size to be 150 or 180.  
2. Searched this error in this forum, people encountered this when they were importing csv files or when they mistakenly added "Database.Stateful" keyword.

I don't quite understand the heap limit here, for each batch, what is the limit?  How can I know which part of my code comsumes most of the heap so I can try to fix my code?
Thank you!

 
global class ContactsCleaning implements Database.Batchable<sObject>,Database.Stateful{
    //query: select id,Accountid,email from Contact where email !=null and email!='\'\'' and accountid!=null and accountid!='\'\''
    public Map<AccountEmail,List<Contact>> duplicatePairs=new Map<AccountEmail,List<Contact>>();
    public integer totalemail=0;
    public integer totalcontact=0;
    global final String query;
    global ContactsCleaning(String q){
        query=q;
    }    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Contact> scope)
    {
        for(Contact c : scope)
        {                        
                //check if email&account pair exists
                AccountEmail ae=new AccountEmail(c.AccountId,c.Email);
                if(duplicatePairs.containsKey(ae))
                {
                    duplicatePairs.get(ae).add(c);                  
                }
                else
                {                    
                    List<Contact> cl=new List<Contact>();
                    cl.add(c);
                    duplicatePairs.put(ae, cl);                    
                }            
        }                
    }    
    global void finish(Database.BatchableContext BC)
    {
        Document d=new Document();
        d.Name='Duplicate Emails';
        d.folderid = UserInfo.getUserId();
        String content='';
        for(AccountEmail ae : duplicatePairs.keySet())
        {
            if(duplicatePairs.get(ae).size()<=1)
            {
                duplicatePairs.remove(ae);
            }
            else
            {
                List<Contact> ls=duplicatePairs.get(ae);
                content=content+'Account: '+ae.AccountID+'   '+'Email:   '+ae.Email+'   ';
                Integer i=1;
                for(Contact c : ls)
                {
                    content=content+i+'   '+'ContactId:  '+c.Id+'   ';
                    i++;
                }
                content+='\n';
            }
        }
        d.Body=Blob.valueOf(content);
        d.ContentType='text/plain';
        d.Type='txt';
        insert d;
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'jack.wang@accelerationretirement.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Duplicate Email Stats');
        mail.setPlainTextBody('Total Contacts:   '+totalcontact+'\n'+'Total Emails:   '+totalemail+'\n'+'Deplicate Pairs:   '+duplicatePairs.size());
        mail.setHtmlBody('<div>Total Contacts:   '+totalcontact+'</div>'+'Total Emails:   '+totalemail+'</div><div>Deplicate Pairs:   '+duplicatePairs.size()+'</div>');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });                                
    }    
}
//This class is the key to dedup email of Contact
public class AccountEmail {
    public String AccountID;
    public String Email;
    public AccountEmail()
    {
    }
    public AccountEmail(String acctid,String e)
    {
        AccountID=acctid;
        Email=e;
    }
    public Boolean equals(Object obj) {
        if (obj instanceof AccountEmail) {
            AccountEmail p = (AccountEmail)obj;
            return ((AccountID==p.AccountID) && (Email==p.Email));
        }
        return false;
    }

    public Integer hashCode() {
        return (31 * AccountID.hashCode()) ^ (Email.hashCode());
    }

}






 
I'm a graduate student of Computer Science gradating this December. 
Have 1 year experience with Salesforce, before that have work experience with .net.
Wrote VF pages, triggers, Batch apex, scheduled apex, workflows, approval processes.
Taking 401 certification in a month.

If you know any open positions please contact me.

/*
 * **Created by Jack Wang 9.24.2014
*/
global class AR_Creating75DummyNML implements Database.Batchable<sObject>{
    
    static final Integer numofNML=75;
    global final String query;
    global AR_Creating75DummyNML(String q)
    {
        query=q;
    }
    
    public List<Task> createNML(List<ID> IDs)
    {
        integer size=IDs.size();
        List<integer> ints=new List<integer>();
        
        Integer numberDays = date.daysInMonth(Date.today().year(), Date.today().month());
        for(integer i=0;i<75;i++)
        {
            double k=Math.random()*size;
            ints.add(k.intValue());          
        }
        
        
        string userid=null;
        User[] users=[select id from User where name='Jeremy Young'];
        if(users.size()>0)
        {
            userid=users[0].id;
        }
        List<Task> tsks=new List<Task>();
        for(Integer i : ints)
        {
            double datek=Math.random()*numberDays;
            Task nml=new Task(ownerid=userid,CallType__c='NML',whatid=String.valueOf(IDs[i]),Subject='NML',
                              Status='Completed',Priority='Normal',ActivityDate=Date.today().tostartofMonth().addDays(datek.intValue()));
            tsks.add(nml);
        }
        return tsks;
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {        
        return Database.getQueryLocator(query);        
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope)
    {
        
        Map<String,List<ID>> territoryClientIDMap=new Map<String,List<ID>>();
        for(Account client : scope)
        {
            if(territoryClientIDMap.containsKey(client.client_territories__c))
            {
                territoryClientIDMap.get(client.client_territories__c).add(client.Id);
            }
            else
            {
                territoryClientIDMap.put(client.client_territories__c, new List<ID>());
                territoryClientIDMap.get(client.client_territories__c).add(client.Id);
            }
        }
        
        for(List<ID> clientIDS : territoryClientIDMap.values())
        {
            List<Task> tsks=createNML(clientIDS);
            insert tsks;
        }
        
        
    }
    
    global void finish(Database.BatchableContext BC)
    {
        
    }

}
@isTest
private class Test_AR_Creating75DummyNML {
    
    
    static testMethod void Test(){
        //create 10 advisors
        ////for each advisor create 100 clients
        //

        string userid=null;
        User[] users=[select id from User where name='Jeremy Young'];
        if(users.size()>0)
        {
            userid=users[0].id;
        }
        List<Account> advisors=new List<Account>();
    
        For(integer i=0;i<10;i++)
        {
            Account a=new Account(name='a'+String.valueOf(i),client_territories__c='a'+String.valueOf(i),account_type__c='provider',Monthly_Activity_Reporting__c=true,Account_Status__c='active');
            advisors.add(a);
        }
        insert advisors;
        
        For(integer j=0;j<advisors.size();j++)
        {
            List<Account> clients=new List<Account>();
            For(integer i=0;i<100;i++)
            {
                Account client=new Account(name=advisors[j].name+String.valueOf(i),client_territories__c=advisors[j].client_territories__c,account_type__c='prospect');
                clients.add(client);
            }
            insert clients;
        }
        
        
        List<Account> advisors1= [select client_territories__c from Account where
                                (account_type__c='provider' or account_type__c='advisor') 
                                 and Monthly_Activity_Reporting__c=true and Account_Status__c='active'];
        List<String> territories=new List<String>();
        List<String> advisorIDs=new List<String>();
        for(Account advisor : advisors1)
        {
            territories.add(advisor.client_territories__c);
            advisorIDs.add(advisor.id);
        }        
        //[select id,client_territories__c from Account where client_territories__c in :territories];
        string tempquery='Select id,client_territories__c from Account where client_territories__c in (';        
        for(String terr : territories)
        {
            tempquery+='\'';
            tempquery+=terr;
            tempquery+='\',';
        }
        tempquery=tempquery.substring(0, tempquery.length()-1);
        tempquery+=') and id not in (';
        for(String adid : advisorIDs)
        {
			tempquery+='\'';
            tempquery+=adid;
            tempquery+='\'';
            tempquery+=',';
        }
        string query=tempquery.substring(0, tempquery.length()-1);
        query+=')';
        
        Test.startTest();
        AR_Creating75DummyNML c=new AR_Creating75DummyNML(query);
        Database.executeBatch(c);
        Test.stopTest();
        
        List<Task> tsk=[select ownerid,CallType__c,Subject,
                              Status,Priority,ActivityDate from Task where createddate=TODAY and CallType__c='NML'
                       and ownerid= :userid and Status='Completed' and Priority='Normal'];
        
        //75 tasks for each advisor
        System.assertEquals(750, tsk.size());
        
        
	}

}

I tried to google this error, but I didn't get a satisfied answer.


  • September 24, 2014
  • Like
  • 0
I have two types of Account, advisor and client.
Each advisor has 3000 clients.  I want to get the 75 random clients and use their ids to create 75 tasks. 

//1 query 36 result rows
List<Account> advisors=[select id,account_type__c,client_territories__c from Account where account_type__c='advisor'];

for(Account a : advisors)
{
    //result rows too large, over 50000
    //For each advisor, create a list of its clients Account
    List<Account> clients=[select id from Account where client_territories__c=:a.client_territories__c];
    
    //Here I want to randomly pick 75 Account Ids and use that as whatid to create 75 Tasks
    
    //If I use the "Limit" Key word in the query, it will not generate random records right?

    
    
} 
  • September 22, 2014
  • Like
  • 0
User-added image

I am trying to build a report in apex and send an html email.
The report is basicly counting records number. But it has cross queries.
Can you look my code and comments and give me some advice?

Thank you!
  • September 20, 2014
  • Like
  • 0

Can anyone teach me how to fix this query?

List<Account> advisors=[select id,client_territories__c,name from Account where ......];
for(Account a : advisors)

      List<Account> a1=[select id from Account where client_territories__c=:a.client_territories__c];
      ..........
      ........

}

I want to avoid wrting queries in For Loop.
So I want to fix the query this way:
List<Account> advisors=[select id,client_territories__c,name,[select id from Account where client_territories__c=?????] from Account where ......];

I'm stucked here.
 

  • September 19, 2014
  • Like
  • 0
I have been analyzing this topic for quite a few days.

The problem I am now facing is:

I have a custom Object "Task_Flow_Manager" on Account Detail page .
On clicking 'new' button of "Task_Flow_Manager", I am directed to a bridge page for selecting record type.
After selecting the record type, I click "continue" button to be directed to the real page for creating new object of "Task_Flow_Manager"

On the page for creating "Task_Flow_Manager", I have quite a lot Lookup fields related to dates or User object  to be populated.

A lot of solutions require URL hacking.
But I can not customize the 'new' button since it resides on a bridge page.

I also tried to set the value by using JavaScript "getelementByID", but somehow failed.

I am trying to create a Visualforce page myself and provide values to populate those Lookup fields
by using an Extension method.

However, I don't know how to give the "Apex:Inputfield" component a default value.