• Blake Tanon
  • NEWBIE
  • 299 Points
  • Member since 2012


  • Chatter
    Feed
  • 10
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 15
    Questions
  • 100
    Replies
I am exporting data from one Salesforce org to another. I have come to tasks and for some reason I got stuck och mass emails. That is tasks that in the SF-GUI are present in the activity history of an object like contact or account for example. When I create a query via a data loader the tasks are not in scope. When I use the workbench and create a SOQL-query I cannot see these tasks. I know they are there but they don't show in any results.
For example use this SOQL-query in the workbench
select id,subject from Task where Subject like 'Mass%'
It gives me zero result.

A similar query gives me result as expected.
select id,subject from Task where Subject like 'Email%'

Now, why is that?

Thanks / Niklas
Hi Everbody,
I am new to apex, so please be patient. This is my first try at coding. Any help I could get is very much appreciated. I created a custom object (DataTable). This object does not have any parent/child relationships. I am trying to "copy" some information from Tasks into this custom object if the Task is related to an Opportunity. For now, all I want is to populate a field ( called TaskSubject__c) in my custom object that is equal to Subject on the Task/Activity object. Thank You! Here is what I got....

trigger AutoCreateDT on Task (after insert) {
for (Task t : Trigger.new) {
// Check if Task is related to Opportunity
if (t.what =='Opportunity') {
//Populate task subject in custom object called DataTable
DataTable d = new DataTable ();
d.TaskSubject__c = t.subject;

}
}
}
  • March 28, 2015
  • Like
  • 0
When saving my visualforce page email template, I recieve the following Error: Unknown property 'core.email.template.EmailTemplateComponentController.CampaignMember'.

Visualforce Email Template
<messaging:emailTemplate subject="PDR Generated Prospect is Available for Follow-Up PDR: NA - South Central Seek List" recipientType="User" relatedToType="CampaignMember">
<messaging:htmlEmailBody >
     <html>
        <body>
         <STYLE type="text/css">
               TH {font-size: 14px; font-face: arial;background: #CCCCCC; border-width: 1;  text-align: center }
               TD  {font-size: 14px; font-face: verdana }
               TABLE {border: solid #CCCCCC; border-width: 1}
               TR {border: solid #CCCCCC; border-width: 1}
         </STYLE>
                  <font face="arial" size="3"></font>
        <p>Dear Salesforce User,</p>
        <p>New PDR Generated prospect(s)have been assigned to a your <b>PDR Generated</b> seek list and is now available for follow up in the following <b>Power Dialer</b> seek list:</p>
        <p><b>PDR Generated (NA - South Central)</b></p>
        <p>To launch the seek list, please click on the following link: <apex:outputLink value="https://na6.salesforce.com/{!CampaignMember.id}">{!CampaignMember.Name}</apex:outputLink></p>
<table border="1"></table>
<tr></tr>
<table border="0" >
                 <tr >
                     <th>Prospect First Name</th><th>Prospect Last Name</th><th> Title </th><th> Phone </th><th> Email </th><th> State </th><th> Country </th><th>Company Name</th><th> Marketing Source</th>
                 </tr>
    <apex:repeat var="cm" value="{!relatedTo.CampaignMember}">
       <tr>
           <td>{!cm.FirstName}</td>
           <td>{!cm.LastName}</td>
           <td>{!cm.Title}</td>
           <td>{!cm.Phone}</td>
           <td>{!cm.Email}</td>
           <td>{!cm.State}</td>
           <td>{!cm.Country}</td>
           <td>{!cm.CompanyOrAccount}</td>
           <td>{!cm.Campaign}</td>
           </tr>
    </apex:repeat>               
       </table>
        </body>
    </html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>

I am recieving the following error but I am not sure why because I  have "</body" at the bottom of the page. 

Error Error: PDR_South_Central line 10, column 20: The element type "body" must be terminated by the matching end-tag "</body>"
Error Error: The element type "body" must be terminated by the matching end-tag "</body>".

Visualforce Email Template:
<messaging:emailTemplate subject="PDR Generated Prospect is Available for Follow-Up PDR: NA - South Central Seek List" recipientType="User" relatedToType="CampaignMember">
<messaging:htmlEmailBody > 
     <html>
        <body>
         <STYLE type="text/css">
               TH {font-size: 14px; font-face: arial;background: #CCCCCC; border-width: 1;  text-align: center }
               TD  {font-size: 14px; font-face: verdana }
               TABLE {border: solid #CCCCCC; border-width: 1}
               TR {border: solid #CCCCCC; border-width: 1}
         </STYLE></p>
                  <font face="arial" size="3">
        <p>Dear Salesforce User,</p>
        <p>New PDR Generated prospect(s)have been assigned to a your <b>PDR Generated</b> seek list and is now available for follow up in the following <b>Power Dialer</b> seek list:<p>
        <p><b>PDR Generated (NA - South Central)</b></p>
        <p>To launch the seek list, please click on the following link: <apex:outputLink value="https://na6.salesforce.com/{!relatedTo.id}">{!relatedTo.Name}</apex:outputLink></p>
<table border="1" >
<tr>
<table border="0" >
                 <tr >
                     <th>Prospect First Name</th><th>Prospect Last Name</th><th> Title </th><th> Phone </th><th> Email </th><th> State </th><th> Country </th><th>Company Name/th><th> Marketing Source</th>
                 </tr>
    <apex:repeat var="cam" value="{!relatedTo.CampaignMember}">
       <tr>
           <td>{!CampaignMember.FirstName}</td>
           <td>{!CampaignMember.LastName}</td>
           <td>{!CampaignMember.Title}</td>
           <td>{!CampaignMember.Phone}</td>
           <td>{!CampaignMember.Email}</td>
           <td>{!CampaignMember.State}</td>
           <td>{!CampaignMember.Country}</td>
           <td>{!CampaignMember.CompanyOrAccount}</td>
           <td>{!CampaignMember.Campaign})}</td>
           </tr>
    </apex:repeat>                
       </table>
        </body>
    </html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
Hi,

I have been trying to create a way of allowing my users to edit only the price books I want them to and this has led me down the path of creating a visualforce page and custom controller

Although I have a range of programming experience, I am still relatively new to both VF and Apex.  What I have is something of a cobbled together mash-up of code found through the website, so do please feel free to point out inconsistencies.

Here is my code:
[code]
<apex:page Controller="Custom_pricebookentry_controller">
    <apex:form>
        <apex:pageBlock>
            <apex:pageBlockSection >
                <apex:inputField value="{!pricebook_List.pricebook2Id}"/>
                <apex:inputField value="{!SearchCriteria.CurrencyIsoCode}"/>
                <apex:commandButton value="Search" action="{!filterPBEs}" reRender="pbe_section,error"/>
                <apex:commandButton value="Save" action="{!save}"/>
            </apex:pageBlockSection>

            <apex:pageBlockTable value="{!filteredPBEs}" id="pbe_section" var="pbe">
                <apex:column headerValue="Name"><apex:outputField value="{!pbe.name}"/></apex:column>
                <apex:column headerValue="Ccy"><apex:outputField value="{!pbe.currencyIsoCode}"/></apex:column>
                <apex:column headerValue="Price"><apex:outputField value="{!pbe.unitPrice}"/></apex:column>
                <apex:column headerValue="New Price"><apex:inputField value="{!pbe.unitPrice}"/></apex:column>
            </apex:pageBlockTable>
           
            <apex:pageMessages id="error"></apex:pageMessages>

        </apex:pageBlock>
    </apex:form>
</apex:page>
[/code]

and

[code]
public with sharing class Custom_pricebookentry_controller {
    public List<priceBookEntry> FilteredPBEs{get;set;}
    public priceBookEntry SearchCriteria{get;set;}
    public opportunity pricebook_list{get;set;}
    public Custom_pricebookentry_controller ()
    {
        pricebook_list = new opportunity();
        SearchCriteria = new priceBookEntry();
    }
   
    public void filterPBEs()   
    {
        FilteredPBEs = new List<priceBookEntry>();
       
        FilteredPBEs = [SELECT Name,UnitPrice
                          FROM PricebookEntry
                         WHERE Pricebook2Id =: pricebook_list.Pricebook2Id
                           AND CurrencyIsoCode =: SearchCriteria.CurrencyIsoCode];
         if(FilteredPBEs.size() == 0)
         {
            Apexpages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,''+'No records to Display'));
         }
    }
   
    public void save()   
    {
        priceBookEntry pbe= new priceBookEntry();

        try
        {
            insert pbe.unitPrice;
        }
        catch(Exception ex)
        {
          System.debug('\n\nException ='+ex.getMessage()+'\n\n');
        }

    }
}
[/code]

Right now I get an error "Error: Compile Error: DML requires SObject or SObject list type: Decimal at line 31 column 13", so presumably I have to define the variable type somehow.

Any help would be hugely appreciated.

David
Hey Everyone,

Recently a new error has come up when one of my batch classes runs causing trades from the day before not to post. This code has worked fine since implemented over 6 months ago. I've never dealt with a Heap Size error before so I'm not sure how to fix it. From what I've researched it involves having to many objects, but the code seems pretty efficient. Unless it's the test class, I don't know where the problem would be. Please take a look and let me know if you can help!

Error:
Trades_CascadeAccounts: System.LimitException: Apex heap size too large: 6220442
Trades_CascadeAccounts: System.LimitException: Apex heap size too large: 6220442
Trades_CascadeAccounts: System.LimitException: Apex heap size too large: 6220442
Trades_CascadeAccounts: System.LimitException: Apex heap size too large: 6220442
Trades_CascadeAccounts: System.LimitException: Apex heap size too large: 6220442

Apex Class:

public class Account_RollupTrades {
    public Static Account_Setting__c setting = Account_Setting__c.getInstance();
    public Static boolean inprog = false;
   
    public static void execute (Set<Id> accountIds, List<Account> accountsList) {
        Map<Id, Account> accounts = new Map<Id, Account> (AccountsList);
        system.debug ('execute');
        if(setting.Disable_RollupTrades__c != true) {
            //Map<Id, Account> accounts = new Map<Id, Account>();
            for(Id accountId:accountIds) {
                system.debug(accountid);
                accounts.put(accountId,
                   new Account(
                       Id=accountId,
                       YTD_NIOR_I_Sales__c = 0,         YTD_NIOR_I_Shares__c = 0,         QTD_NIOR_I_Sales__c = 0,         QTD_NIOR_I_Shares__c = 0,
                       MTD_NIOR_I_Sales__c = 0,         MTD_NIOR_I_Shares__c = 0,         PY_NIOR_I_Sales__c = 0,          PY_NIOR_I_Shares__c = 0,
                       Total_NIOR_I_Sales__c = 0,       Total_NIOR_I_Shares__c = 0,       YTD_NS_Income_Sales__c = 0,      YTD_NS_Income_Shares__c = 0,
                       QTD_NS_Income_Sales__c = 0,      QTD_NS_Income_Shares__c = 0,      MTD_NS_Income_Sales__c = 0,      MTD_NS_Income_Shares__c = 0,
                       PY_NS_Income_Sales__c = 0,       PY_NS_Income_Shares__c = 0,       Total_NS_Income_Sales__c = 0,    Total_NS_Income_Shares__c = 0,
                       Total_NS_HI_Sales__c = 0,       Total_NS_HI_Shares__c = 0,       YTD_NS_HI_Sales__c = 0,         YTD_NS_HI_Shares__c = 0,
                       QTD_NS_HI_Sales__c = 0,         QTD_NS_HI_Shares__c = 0,         MTD_NS_HI_Sales__c = 0,         MTD_NS_HI_Shares__c = 0,
                       PY_NS_HI_Sales__c = 0,          PY_NS_HI_Shares__c = 0,          Total_NS_Income_II_Sales__c = 0, Total_NS_Income_II_Shares__c = 0,
                       YTD_NS_Income_II_Sales__c = 0,   YTD_NS_Income_II_Shares__c = 0,   QTD_NS_Income_II_Sales__c = 0,   QTD_NS_Income_II_Shares__c = 0,
                       MTD_NS_Income_II_Sales__c = 0,   MTD_NS_Income_II_Shares__c = 0,   PY_NS_Income_II_Sales__c = 0,    PY_NS_Income_II_Shares__c = 0,
                       Rollup_Trades__c = DateTime.now()
                   )
                            );
            }
           
        // Roll up the trades based on the Resolved Firm Trading ID field
        Trades__c[] tradesList = [
            select Dollar_Amount_of_the_transaction__c, Fund_Number__c, Number_of_Shares_of_the_transaction__c,
                Resolved_to_Rep_Trading_ID__c, Resolved_Firm_Trading_ID__c, Resolved_Firm_Trading_IDs__c,
                Trade_Date__c
              from Trades__c
             where Resolved_Firm_Trading_ID__c in :accountIds
               and Fund_Number__c in ('3910', '3911', '3912', '3915')       // NIOR I; NS Income; NS HI; NS Income II
               and Dollar_Amount_of_the_transaction__c != null      // prevents null pointers below
               and Number_of_Shares_of_the_transaction__c != null   // prevents null pointers below
               and Trade_Date__c != null                            // prevents null pointers below
               // Negative values are ignored for roll-up purposes
               and Dollar_Amount_of_the_transaction__c >= 0
               and Number_of_Shares_of_the_transaction__c >= 0
        ];
           
            Map<String, SObjectField[]>
                ytd = new map<string, sobjectfield[]> {
                    '3910' => new sobjectfield[] { account.YTD_NIOR_I_Sales__c , account.YTD_NIOR_I_Shares__c},
                    '3911' => new sobjectfield[] { account.YTD_NS_Income_Sales__c , account.YTD_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.YTD_NS_HI_Sales__c , account.YTD_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.YTD_NS_Income_II_Sales__c , account.YTD_NS_Income_II_Shares__c }   
                },
                qtd = new map<string, sobjectfield[]> {
                    '3910' => new sobjectfield[] { account.QTD_NIOR_I_Sales__c , account.QTD_NIOR_I_Shares__c},
                    '3911' => new sobjectfield[] { account.QTD_NS_Income_Sales__c , account.QTD_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.QTD_NS_HI_Sales__c , account.QTD_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.QTD_NS_Income_II_Sales__c , account.QTD_NS_Income_II_Shares__c }
                },
                mtd = new map<string, sobjectfield[]> {
                    '3910' => new sobjectfield[] { account.MTD_NIOR_I_Sales__c , account.MTD_NIOR_I_Shares__c},
                    '3911' => new sobjectfield[] { account.MTD_NS_Income_Sales__c , account.MTD_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.MTD_NS_HI_Sales__c , account.MTD_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.MTD_NS_Income_II_Sales__c , account.MTD_NS_Income_II_Shares__c }
                },
                py = new map<string, sobjectfield[]> {
                    '3910' => new sobjectfield[] { account.PY_NIOR_I_Sales__c , account.PY_NIOR_I_Shares__c},
                    '3911' => new sobjectfield[] { account.PY_NS_Income_Sales__c , account.PY_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.PY_NS_HI_Sales__c , account.PY_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.PY_NS_Income_II_Sales__c , account.PY_NS_Income_II_Shares__c }
                },
                total = new map<string, sobjectfield[]> {
                    '3910' => new sobjectfield[] { account.Total_NIOR_I_Sales__c , account.Total_NIOR_I_Shares__c},
                    '3911' => new sobjectfield[] { account.Total_NS_Income_Sales__c , account.Total_NS_Income_Shares__c },
                    '3912' => new sobjectfield[] { account.Total_NS_HI_Sales__c , account.Total_NS_HI_Shares__c },
                    '3915' => new sobjectfield[] { account.Total_NS_Income_II_Sales__c , account.Total_NS_Income_II_Shares__c }
                };

            for(trades__c trade:tradesList) {
                if(date.today().year() == trade.trade_date__c.year()) {
                    accounts.get(trade.Resolved_Firm_Trading_ID__c).put(ytd.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(ytd.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
                    accounts.get(trade.Resolved_Firm_Trading_ID__c).put(ytd.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(ytd.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);

                    if( (Decimal.ValueOf(date.today().month()).divide(3, 0) == Decimal.ValueOf(trade.trade_date__c.month()).divide(3, 0)) )   {
                        accounts.get(trade.Resolved_Firm_Trading_ID__c).put(qtd.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(qtd.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
                        accounts.get(trade.Resolved_Firm_Trading_ID__c).put(qtd.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(qtd.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);

                        if(date.today().month()==trade.trade_date__c.month()) {
                            accounts.get(trade.Resolved_Firm_Trading_ID__c).put(mtd.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(mtd.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
                            accounts.get(trade.Resolved_Firm_Trading_ID__c).put(mtd.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(mtd.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);
                        }
                    }
                } else if(date.today().year()-1==trade.trade_date__c.year()) {
                    accounts.get(trade.Resolved_Firm_Trading_ID__c).put(py.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(py.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
                    accounts.get(trade.Resolved_Firm_Trading_ID__c).put(py.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(py.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);
                }
                accounts.get(trade.Resolved_Firm_Trading_ID__c).put(total.get(trade.fund_number__c)[0], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(total.get(trade.fund_number__c)[0]))+trade.Dollar_Amount_of_The_Transaction__c);
                accounts.get(trade.Resolved_Firm_Trading_ID__c).put(total.get(trade.fund_number__c)[1], ((Decimal)accounts.get(trade.Resolved_Firm_Trading_ID__c).get(total.get(trade.fund_number__c)[1]))+trade.Number_of_Shares_of_the_transaction__c);
            }
        }
     inprog = true;
     update accounts.values();
     inprog = false;
    }
}


Apex Trigger:

trigger Account_RollupTrades on Account (after update) {
    if(Account_RollupTrades.inprog == false) {
        set<ID> sID = new set<ID> (trigger.newMap.keySet());
        Account_RollupTrades.execute(sID, trigger.new);
    }
}

This is my first attempt at writing a Salesfroce trigger so please bear with me.
 
The company I work for has three different brands that all use the same Salesfoce account.  Each brand has several sales reps that cross-sell different products within their specific brand but DO NOT cross-sell between brands.  It is important that each sales rep within each brand maintains ownership of their lead whenever a new form submission comes in and the Principle Interest matches their brand.   I am trying to write an Apex trigger that will do the following when a new form submission comes in.

1.) Check for a duplicate email address in Salesforce.
2.) If a duplicate email address is found it will then compare the Principle Interest of the record currently in the database with the Priniciple Interest of the incoming form.
3.) If the Principle Interests match then the current record is updated in the database and the lead owner is left unchanged.  If they don't match then a new lead record is created using the information from the form submission and a new lead owner is assigned.

I think I have # 1 and #2 taken care of but #3 is givining me a lot fo difficulty.

This is the trigger I have written so far.

trigger SetLeadOwner on Lead (before insert) {
   for (Lead myLead : Trigger.new) {
       
            List<Lead> dupesLead = [
                SELECT Id, Principle_Interest__c
                FROM Lead
                WHERE Email = :myLead.Email
            ];
       
         Set<String> BrandOneSet = new Set<String>();
                List<String> BrandOneList = new List<String>();
                BrandOneList.add('PrincipleInterest1');
                BrandOneList.add('PrincipleInterest2');
                BrandOneList.add('PrincipleInterest3');
            BrandOneSet.addAll(BrandOneList);
           
            Set<String> BrandTwoSet = new Set<String>();
                List<String> BrandTwoList = new List<String>();
                BrandTwoList.add('PrincipleInterest4');
                BrandTwoList.add('PrincipleInterest5');
                BrandTwoList.add('PrincipleInterest6');
                BrandTwoList.add('PrincipleInterest7');
                BrandTwoList.add('PrincipleInterest8');
                BrandTwoList.add('PrincipleInterest9');
            BrandTwoSet.addAll(BrandTwoList);
           
            Set<String> BrandThreeSet = new Set<String>();
                List<String> BrandThreeList = new List<String>();
                BrandThreeList.add('PrincipleInterest10');
                BrandThreeList.add('PrincipleInterest11');
                BrandThreeList.add('PrincipleInterest12');
            BrandThreeSet.addAll(BrandThreeList);
        
        if(myLead.email != null){
            if (dupesLead.size() == 0) { // check for duplicate emails.  if none found, create new lead.
                // insert myLead;
            } else if (dupesLead[0].Principle_Interest__c == myLead.Principle_Interest__c) {
                update dupesLead[0];
            } else if (BrandOneSet.contains(myLead.Principle_Interest__c) && BrandOneSet.contains(dupesLead[0].Principle_Interest__c)) {
                update dupesLead[0];
            } else if (BrandTwoSet.contains(myLead.Principle_Interest__c) && BrandTwoSet.contains(dupesLead[0].Principle_Interest__c)) {
                update dupesLead[0];
            } else if (BrandThreeSet.contains(myLead.Principle_Interest__c) && BrandThreeSet.contains(dupesLead[0].Principle_Interest__c)) {
                update dupesLead[0];
            } else { // What happens if the Principle Interests don't match up
                // insert myLead;
            }
        } // End (myLead.email != null)
} // End (Lead myLead : Trigger.new)
}

Any help would be greatly appreciated.

Thanks,
Eric

  • March 19, 2014
  • Like
  • 0
In going through the triggers I have created, I noticed that I have created multiple trigger for the same objects.  Moving forward, is it better to create any new triggers for an object in an existing trigger, or is it ok to continue creating additional triggers on the same object.

Anyone who can help!

 

I'm trying to create a  cloud flow design that would that would trigger based on the status of a Lead or  Contact record. Which in turn would check a custom object to see if a record exist if it doesn't it then creates a record....The flow would be as follows:

 

Lead or Contact record becomes (Sales Qualified) ---->  Check to see if this record has a Qualified Lead Record (custom object), if false then create new Qualified Lead Record.

 

Any help would be greatly appreciated.

 

-KG

To warn you I am new to apex.  Here is my situation.  I have created a flow (not workflow but flow) that my salesguys use for their sale.  Right now I have created a button that is labeled Start Sale.  I have placed the button on the lead and the button is just a url that goes to /flow/Sales_Flow which is the flow.  The salesguys have to copy the ID out of the address bar on the lead to get the ID of the lead into my flow.  I am hoping to create an apex button or code of some sort that will take the ID of the lead that the button is on and put that ID into a field that populates a variable called leadID in my flow.  I figure there has got to be a way to have that variable populated when the flow starts so that they do not have to copy it, but I cannot figure out how to do it.

Thanks for the help.

I have a batch that's been running for years that started failing because of First error: Access to entity 'MatchingInformation' denied.  I've searched around and can't find anything about this and I can't find any object or class in salesforce called MatchingInformation.  It doesn't happen each time this batch runs, it seems to be arbitrary and can happen with any set of arguments.  The batch is below, simply it updates a list of records with a defined value.
 
global class util_sObjectFieldUpdaterBatch implements Database.Batchable<sobject>, Database.Stateful {

    /**
    Run This Batch

    string query = ;
    string nextBatch = ;
    string sObj = ;
    string field = ;
    object changeTo = ;
    integer batSize = ;
    
    ID idBatch = Database.executeBatch(new util_sObjectFieldUpdaterBatch(query,nextBatch,sObj,field,changeTo), batSize);
    **/

    global string query;
    global string nextBatch;

    global string sObjName;
    global string sObjFieldName;
    global sObjectType sObjType;
    global sObjectField sObjField;

    global object changeTo;

    private Map<String, Schema.SObjectType> smap = Schema.getGlobalDescribe();

    global integer NumBatches;
    
    global util_sObjectFieldUpdaterBatch(String qry, string nextBat, string obj, string field, object changeObj) {

        Query = qry;
        
        nextBatch = nextBat;

        sObjName = obj;
        
        changeTo = changeObj;

        SObjectType sObjType;

        if(smap.get(obj) != null){

            sObjType = smap.get(obj);

            Map<String,Schema.SObjectField> fieldMap = sObjType.getDescribe().fields.getMap(); 

            if(fieldMap.get(field) != null){
                
            	sObjFieldName = field;

            	sObjField = fieldMap.get(field);

            }

        }

    }
    
    global Database.QueryLocator start(Database.BatchableContext bcMain) {
        return Database.getQueryLocator(Query);
    }
    
    global void execute(Database.BatchableContext bcMain, List<sObject> scope) {

        for(sObject s : scope){
        	s.put(sObjField, changeTo);
        }

        if(scope.size() > 0) { 
            update scope; 
        }
    }
    
    global void finish(Database.BatchableContext bcMain) {

    } 
	
}

 
I'm running into time limits with query around tasks, one of the transactions I'm trying to execute is gathering a count of tasks that fall in the below query.  The query is run in a trigger when (1) only 1 record is being updated and (2) when a checkbox is true.

-----
for(aggregateResult r:[SELECT count(id), ownerid FROM task WHERE isclosed = true and month_ending__c =: me AND ownerId =: uid
       AND outcome__c = 'Success' AND call_score__c in ('1','2')
       AND activity_type__c = 'Call'

       GROUP BY ownerid  LIMIT 300])

 s.Score_Value__c = integer.valueof(r.get('expr0'));
-----

The trigger is run off a custom object called Scorecard__c
  • Variables:
    • me = Date, Month_ending(date) on scorecard__c
    • uid = id, custom user field on scorecard
  • Task fields
    • month_ending__c = date field
    • outcome__c = picklist
    • call_score__c = picklist
    • activity_type__c = text/external ID
There are 767,147 tasks in SFDC as of right now.  I can't figure out how to make this query more selective, it was a custom indexed field (activity_type__c) and a standard index (ownerid).  Neither hit the optimizer threshold limit.

Any thoughts?

I"ve been racking my brain over this for a while so it's time to ask for some help.  I'm tring to query a list in a Class to display on a VF page, but when I put a variable into the SubQuery in the Where clause I don't get any results, however if i just put in a record ID it works.  

 

global class DistributionExtentionRepMonthlyReport_C{

public static list<contact> cList;


    public DistributionExtentionRepMonthlyReport_C(){
    //public void runQuery(){
        
            cList = [SELECT id, FirstName, LastName, OtherStreet, OtherCity, OtherState, OtherPostalCode,
                         Account.Name, CRD__c
                     FROM contact
                     WHERE id in (SELECT rep__c
                                  FROM distribution_history__c
                                  WHERE distribution__c =: ApexPages.currentPage().getParameters().get('id'))
                     LIMIT 50];


    }

    public static list<contact> getcList(){
        return clist;
    }


}

 

I've got a trigger that currently only works on single updates - but really needs to be written to work in bulk.  The trigger is on a custom object called Transaction__c which houses our sales records, in regards to this case it's a child to Contacts.  The purpose of it is to get the number of Calls(Tasks), Successful Calls(Tasks), Meetings(Events) and Kits(Order__c) that where placed within a time frame related to the contact that is linked to the transaction record.

 

The issue is that the aggregate map queries are being run and storied for the first record in the batch, so the next 199 (or whatever the bacth size is -1) are receiving null values.  

 

Any points on the direction I need to take?

 

trigger TransactionScoring on Transaction__c(before update) {

// Build the maps for the Count and ActivityDate First
    
    Set<Date> PStart = new Set<Date>();
    for(Transaction__c t:trigger.new)
        PStart.add(t.Trade_Period_Start__c);
        
    Set<Date> PEnd = new Set<Date>();
    for(Transaction__c t:trigger.new)
        PEnd.add(t.Trade_Date__c);
      
    Set<Id> cid = new Set<Id>();
    for(Transaction__c t:trigger.new)
        cid.add(t.rep__c);
    

    Map<String,Integer> callCountMap = new Map<String,Integer>();
        for(AggregateResult r:[select COUNT(id), WhoId 
                               from Task 
                               where Whoid in:cid AND (Type = 'Cold Call' OR Type = 'Inbound Call' OR Type = 'Outbound Call') 
                               AND Status = 'Completed' AND isDeleted = False AND 
                               (Date_Completed__c >: PStart AND Date_Completed__c <=: PEnd) AND xOwnerWS__c = true 
                               GROUP BY WhoId 
                               LIMIT 100 ALL ROWS])
            callCountMap.put(String.valueof(r.get('WhoId')),Integer.valueof(r.get('expr0')));
    
    Map<String,Integer> scallCountMap = new Map<String,Integer>();
        for(AggregateResult r:[select COUNT(id), WhoId 
                               from Task 
                               where Whoid in :cid AND (Type = 'Cold Call' OR Type = 'Inbound Call' OR Type = 'Outbound Call')
                               AND Status = 'Completed' AND isDeleted = False AND Outcome__c = 'Success' AND 
                               (Date_Completed__c >: PStart AND Date_Completed__c <=: PEnd) AND xOwnerWS__c = true 
                               GROUP BY WhoId 
                               LIMIT 50 ALL ROWS])
            scallCountMap.put(String.valueof(r.get('WhoId')),Integer.valueof(r.get('expr0')));
    
    
    Map<String,Integer> meetingCountMap = new Map<String,Integer>();
        for(AggregateResult r:[select COUNT(id), WhoId 
                               from Event 
                               where Whoid in :cid AND Outcome__c = 'Meeting Occurred' AND isDeleted = False 
                               AND (Date_Completed__c >=: PStart AND Date_Completed__c <: PEnd) 
                               GROUP BY WhoId 
                               LIMIT 10 ALL ROWS])
            meetingCountMap.put(String.valueof(r.get('WhoId')),Integer.valueof(r.get('expr0')));
        
    Map<String,Integer> kitCountMap = new Map<String,Integer>();
        for(AggregateResult r:[select sum(number_of_kits__c), contact__c 
                               from Order__c 
                               where contact__c in :cid AND Status__c = 'Shipped' 
                               AND (Order_Date__c >=: PStart AND Order_Date__c <: PEnd) 
                               GROUP BY contact__c LIMIT 10 ALL ROWS])
            kitCountMap.put(String.valueof(r.get('contact__c')),Integer.valueof(r.get('expr0')));


    // Iterate over the Trigger.new List and check if the Id exists in  the Map and assign value from Map       
  for(Transaction__c c:Trigger.new)  {  
    c.Calls__c = 0;
    c.Successful_Calls__c = 0;
    c.Meetings__c = 0;
    c.kits__c = 0;
    //c.contact__c = cid;

    if(callCountMap.get(c.rep__c) != null)
        c.Calls__c = callCountMap.get(c.rep__c);
    
    if(scallCountMap.get(c.rep__c) != null)
        c.Successful_Calls__c = scallCountMap.get(c.rep__c);
    
    if(meetingCountMap.get(c.rep__c) != null)
        c.Meetings__c = meetingCountMap.get(c.rep__c);
        
    if(kitCountMap.get(c.rep__c) != null)
        c.Kits__c = kitCountMap.get(c.rep__c);
    
    }
}

 

 

Is there a refernce anywhere with what these error codes are?  It happend when running a test class.

Hello,

 

I've searched far and wide and spent a good time thinking about the best way to solve the below problem, but I'm either not sure how to do them or which would be the best solution.

 

I have a couple of projects I'm working on that require an auto numbering of some sort, but not the auto-numbering field out of the box.  I need child records of a partent to be numbered 1 though n based onspecific critiera, a date field and 2 lookups (date__c, contact__c, fund__c) - if there are multiple records on the same day with the same contact/fund they should be the same number.  That being said, here are the solutions I've come to...

 

1)  Create a workflow that runs off of a count rollup, assigning the number +1 to the new child. 

Problem: not dynamic enough, not enough control on the groupings 

 

2) Use SQL to number the records, this would require a daily export/import to assign the numbers - while this wouldn't be a huge burden on our api I would prefer not to use this method

 

3) Some how do this in java - I don't know java

 

4) use a trigger - I could firgure this out, but I don't think it's the best way.

 

5) use batch apex - not sure how to do this

 

Any ideas?

Hello,

 

I'm a novice programmer at best - trying to teach myself.  I know how to set/declare variables in triggers, but I'm not sure how to go about it in a class.  I'm working on building VF emails and I would like the class to pull a field value from the record that is is generated from.

 

We have a object for Territories (Territory__c), we would like to send out activity reports to our group each night with all of the Tasks and Events completed for that territory.  The salesforce scheduled reports aren't scalable since we need one per territory and can only send one per hour.  I would like to pull the Territory Name field in as a veriable, then query tasks/events that match that - Activities have a field called Territory__c that will match the name.  Here is my class:

 

public class TerritoryActivity{

    private final List<Task> t;
    private final List<Event> e;


    
    public TerritoryActivity(){
        
        
        t = [SELECT id, Territory__c, Assigned_Name__c, Firm_Name__c, Contact_Name__c, State__c,Description, Subject, Outcome__c, Type
             FROM Task
             WHERE Date_Completed__c = Yesterday AND Outcome__c = 'Success' AND Territory__c = 'New England'];
             
        e = [SELECT id, Territory__c, Assigned_Name__c, Firm_Name__c, Contact_Name__c, State__c,Description, Subject, Outcome__c, Type
             FROM Event
             WHERE Date_Completed__c = Yesterday AND Outcome__c = 'Meeting Occurred' AND Territory__c = 'New England'];

    }     
    
    
    public List<Task> getCalls(){
        return t;
    }
    
    public List<Event> getMeetings(){
        return e;
    }        
}

 

I've tried the application in Chrome and Firefox, updated flash and it is still crashing when I attempt to make the smallet adjustments to a flow.  It seems there's no desktop version of the this available anymore either, has anyone else been experiencing issues?

Hello,

I'm getting an error when running a test on the follow piece of code... the underlined piece is where the error is coming from, any ideas on how to correct this?

 

System.DmlException: Update failed. First exception on row 0 with id a07c0000000fbUFAAY; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Trade: execution of BeforeUpdate caused by: line 17, column 1: Illegal empty right operand for operator '<=' in query 'select COUNT(id), WhoId from Task '.: []

 

Set<Date> PStart = new Set<Date>();
    for(Transaction__c t:trigger.new)
        PStart.add(t.Trade_Period_Start__c);
        
    Set<Date> PEnd = new Set<Date>();
    for(Transaction__c t:trigger.new)
        PStart.add(t.Trade_Date__c);
        
    Set<Id> cid = new Set<Id>();
    for(Transaction__c t:trigger.new)
        cid.add(t.rep__c);

    Map<String,Integer> callCountMap = new Map<String,Integer>();
        for(AggregateResult r:[select COUNT(id), WhoId from Task where Whoid in :cid AND (Type = 'Cold Call' OR Type = 'Inbound Call' OR Type = 'Outbound Call') AND Status = 'Completed' AND isDeleted = False AND (Date_Completed__c >=: PStart AND Date_Completed__c <=: PEnd) GROUP BY WhoId LIMIT 100 ALL ROWS])
            callCountMap.put(String.valueof(r.get('WhoId')),Integer.valueof(r.get('expr0')));

 

I have a trigger that updates the number of calls logged against a contact, this part works fine in batch processes.  The second part of the trigger I need to update a date field with the first call date(in red), but it doesn't seem to be working in dataloads.  Any suggestions?

 

 

 

 

trigger CallCount on Contact (before update) {


  for(Contact c:Trigger.new)
    c.Calls__c = 0;
     
  for(Task t:[select id,WhoId from Task where Whoid in :Trigger.new AND (Type = 'Cold Call' OR Type = 'Inbound Call' OR Type = 'Outbound Call') AND Status = 'Completed' AND isDeleted = False AND ActivityDate > 2009-12-31 LIMIT 250 ALL ROWS])

    Trigger.newMap.get(t.WhoId).Calls__c++;
    
   
    for(Contact c:Trigger.new)
    c.First_Call_Date__c = null;
    
    for(Task t:[select activitydate, whoid from task where whoid in:trigger.new AND (Type = 'Cold Call' OR Type = 'Inbound Call' OR Type = 'Outbound Call') AND Status = 'Completed' AND isDeleted = False Order By ActivityDate asc LIMIT 1 ALL ROWS])
        
        trigger.newMap.get(t.whoid).First_Call_Date__c = t.ActivityDate;


}

 

I'm trying to create new layouts, the one I've done for contacts is posted below.  All of the links/functions work when viewing the page normally but when a contact is looked at via the console none of the links work and i'm not sure why.... any ideas?

 

<apex:page action="{!if($User.LastName =='Tanon', null, urlFor($Action.Contact.View,$CurrentPage.parameters.id,null,true))}" standardController="Contact" showHeader="true"  tabStyle="contact">
   <style>
      .activeTab {background-color: #236FBD; color:white; 
         background-image:none}
      .inactiveTab { background-color: lightgrey; color:black; 
         background-image:none}
   </style>
   <apex:tabPanel switchType="client" selectedTab="tabdetails"  id="ContactTabPanel" tabClass="activeTab"  inactiveTabClass="inactiveTab">   
      <apex:tab label="Details" name="ConDetails" id="tabdetails">
         <apex:detail relatedList="false" title="true" inlineEdit="true"/>
      </apex:tab>
      <apex:tab label="Open Activities" name="Activities" id="tabAct">
         <apex:relatedList subject="{!contact}"  list="OpenActivities" />
      </apex:tab>
      <apex:tab label="Activity History" name="ActivitiesHist" id="tabActHist">
         <apex:relatedList subject="{!contact}"  list="ActivityHistories" />
      </apex:tab>
      <apex:tab label="Orders" name="Orders"  id="tabOrder">
         <apex:relatedList subject="{!contact}"  list="Orders__r" pageSize="10"/>
      </apex:tab>
      <apex:tab label="Sales"  name="Sales" id="tabSales">
         <apex:relatedList subject="{!contact}"  list="Transactions__r" pageSize="50"/>
      </apex:tab>
      <apex:tab label="Pipeline"  name="Opportunities" id="tabOpp">
         <apex:relatedList subject="{!contact}"  list="Opportunities"/>

      </apex:tab>
      <apex:tab label="Partnerships" name="Partnerships"  id="tabPartner">
         <apex:relatedList subject="{!contact}"  list="Partner_Members__r" pageSize="10"/>
      </apex:tab>
      
   </apex:tabPanel>
</apex:page>

 

I ran into this error for the first time today with the below trigger, it only happens when recurring tasks are created.  Apex trigger ContactCallBulk caused an unexpected exception, contact your administrator: ContactCallBulk: System.LimitException: Too many SOQL queries: 101.  Any ideas to make this trigger only run on non-recurring tasks or another fix?  

 

I tried to add an if statement to run if IsRecurrence == FALSE and then not true but that didn't work.

 

trigger ContactCallBulk on Task (after insert, after update) {
//Trigger works with bulk apex
//Updates total number of calls on contact
    
    //Get current task Id
    for (Task tn:Trigger.new){
    if(tn.IsRecurrence <> TRUE){
        System.debug('id is: '+tn.id);
        System.debug('subject is: ' +tn.Subject);
    //Map contact related to WhoId
    Map<Id,Contact> parents = new Map<Id,Contact>([SELECT Id FROM Contact WHERE id =:tn.whoid LIMIT 1]);
    
    
    if(Trigger.new<>null)
        for(Task t:Trigger.new){
        if(t.Status == 'Completed'){
        System.debug('id is: '+t.id);
        System.debug('subject is: ' +t.Subject);
            if(t.WhoId<>null)
                parents.put(t.WhoId,new Contact(id=t.WhoId));
        }}
        
    if(Trigger.old<>null)
        for(Task t:Trigger.old){
        if(t.Status == 'Completed'){
        System.debug('id is: '+t.id);
        System.debug('subject is: ' +t.Subject);
            if(t.WhoId<>null)      
                parents.put(t.WhoId,new Contact(id=t.WhoId));
        }}
    update parents.values();
    
    }}
}

 

I've tried to bulkify this trigger but with no success, below is the code that works for single updates.  We use an object other than Opportunities to track our sales and I'm trying to build out a better way to track our ROI on campaigns.  This triggers goal is to get a sum of all sales for the 90 days after a campaign has ended on each campaign member record.  Any pointers?

 

 

 

 

trigger CMPostSales on CampaignMember (before update) {


Integer i = 0;

CampaignMember cm = Trigger.new[i];

// Current CampaignMember and Contact ID
String intCm = Trigger.new[i].Id;
CampaignMember cmm = [Select Contact.id, End_Date__c, Post_Sales__c from CampaignMember where id =: intCm];

//Step 2. Create a list of Transactions who are children of Contact record.
List<Transaction__c> t = [Select Transaction__c.Gross_Amount__c From Transaction__c WHERE Transaction__c.Rep__c =: cmm.Contact.id AND Transaction__c.Trade_Date__c >: cmm.End_Date__c AND Transaction__c.Trade_Date__c <: cmm.End_Date__c + 90];

/* Update Sales within the range of the campaign */
// Loop through the filtered Transactions and sum up their amounts.
    Double a = 0;
        for(Transaction__c tr : t)
            {
            if(tr.gross_Amount__c != Null)
                {
                a += tr.Gross_Amount__c;
                }
            }
        cm.Post_Sales__c  = a;
}

 

 

I'm very new to programming and even newer to apex, I've modified the below code from a sample I found but have no idea how to write a test class for it.  If it is not to difficult would anyone have an idea?

 

trigger SumSalesOnAccount on Account (before update)
{

Integer i = 0;

Account acc = Trigger.new[i];

// Current Account ID
String intTest = Trigger.new[i].Id;



//Step 2. Create a list of Transactions who are children of this Account record.
List<Transaction__c> trn = [Select Transaction__c.Id, Transaction__c.Gross_Amount__c, Transaction__c.Month_Rank__c From Transaction__c where Transaction__c.Firm__c =: intTest AND Transaction__c.Month_Rank__c =: '-1'];

Double a = 0;

// Loop through the filtered Transactions and sum up their amounts.
for(Transaction__c tr : trn)
{
If (tr.Gross_Amount__c != Null)
{
a += tr.Gross_Amount__c;
}
}
acc.Sales_1__c = a;

//Step 2.2. Create a list of Transactions who are children of this Account record.
List<Transaction__c> trn2 = [Select Transaction__c.Id, Transaction__c.Gross_Amount__c, Transaction__c.Month_Rank__c From Transaction__c where Transaction__c.Firm__c =: intTest AND Transaction__c.Month_Rank__c =: '-2'];

Double b = 0;

// Loop through the filtered Tranasctions and sum up their amounts.
for(Transaction__c tr2 : trn2)
{
If (tr2.Gross_Amount__c != Null)
{
b += tr2.Gross_Amount__c;
}
}
acc.Sales_2__c = b;

//Step 2.3. Create a list of Transactions who are children of this Account record.
List<Transaction__c> trn3 = [Select Transaction__c.Id, Transaction__c.Gross_Amount__c, Transaction__c.Month_Rank__c From Transaction__c where Transaction__c.Firm__c =: intTest AND Transaction__c.Month_Rank__c =: '-3'];

Double c = 0;

// Loop through the filtered Tranasctions and sum up their amounts.
for(Transaction__c tr3 : trn3)
{
If (tr3.Gross_Amount__c != Null)
{
c += tr3.Gross_Amount__c;
}
}
acc.Sales_3__c = c;

//Step 2.4. Create a list of Transactions who are children of this Account record.
List<Transaction__c> trn4 = [Select Transaction__c.Id, Transaction__c.Gross_Amount__c, Transaction__c.Month_Rank__c From Transaction__c where Transaction__c.Firm__c =: intTest AND Transaction__c.Month_Rank__c =: '-4'];

Double d = 0;

// Loop through the filtered Tranasctions and sum up their amounts.
for(Transaction__c tr4 : trn4)
{
If (tr4.Gross_Amount__c != Null)
{
d += tr4.Gross_Amount__c;
}
}
acc.Sales_4__c = d;

//Step 2.5. Create a list of Transactions who are children of this Account record.
List<Transaction__c> trn5 = [Select Transaction__c.Id, Transaction__c.Gross_Amount__c, Transaction__c.Month_Rank__c From Transaction__c where Transaction__c.Firm__c =: intTest AND Transaction__c.Month_Rank__c =: '-5'];

Double e= 0;

// Loop through the filtered Tranasctions and sum up their amounts.
for(Transaction__c tr5 : trn5)
{
If (tr5.Gross_Amount__c != Null)
{
e += tr5.Gross_Amount__c;
}
}
acc.Sales_5__c = e;

//Step 2.6. Create a list of Transactions who are children of this Account record.
List<Transaction__c> trn6 = [Select Transaction__c.Id, Transaction__c.Gross_Amount__c, Transaction__c.Month_Rank__c From Transaction__c where Transaction__c.Firm__c =: intTest AND Transaction__c.Month_Rank__c =: '-6'];

Double f = 0;

// Loop through the filtered Tranasctions and sum up their amounts.
for(Transaction__c tr6 : trn6)
{
If (tr6.Gross_Amount__c != Null)
{
f += tr6.Gross_Amount__c;
}
}
acc.Sales_6__c = f;
}

I feel this would be an easy trigger to make, I'm not just a programmer of any sorts.  Here is what I need it to do:

When the parent record (contact) is updated or created, update all child records for partner_member__c.  There won't be anymore than 4 child records in the largest case.  

If anyone could help me with this I'd appreciate it!

Thanks,
Blake

i am trying to tidy my code so that i reduce the number of soqls here is a sample
public  class updatedeletopps {

    public static void updatedelopps(List<Contact> contactIds){
        Id recId = Schema.SObjectType.Easy_Opportunity__c.getRecordTypeInfosByName().get('Residential Sales').getRecordTypeId();
        
        
//n1        
//
        contact[] activecontacts = [select id, active_contact__c from contact where id in :contactIds];
        set<id> activecontactsset = new set<id>();
        for(contact con : activecontacts) 
            if(con.active_contact__c == 'No') 
            	activecontactsset.add(con.Id);

     List<easy_opportunity__c> oppsToUpdate1 = new List<easy_opportunity__c>();
        list<easy_opportunity__c> opptys = [select id, Stage__c, recordtypeid from easy_opportunity__c where Contact_Name__c in: 
		activecontactsset and name = 'Market Appraisal' and stage__c = 'Closed Lost' and recordtypeid = :recId];
     for(easy_opportunity__c opp1 : opptys)
     { 
         opp1.Stage__c='Closed Lost';
         opp1.Opportunity_Lost_Reason__c = 'Lost Contact';
         opp1.Opportunity_Rating__c = 'Cold';
         oppsToUpdate1.add(opp1);
     }

     update oppsToUpdate1;
        
    list<easy_opportunity__c> oppstodelete2 = new list<easy_opportunity__c>();
        list<easy_opportunity__c> opptys1 = [select id, stage__c, recordtypeid from easy_opportunity__c where contact_name__c 

in:activecontactsset and (name =  'Lost MA Upsell - Gas Safety Check' or name = 'Lost MA Upsell - Home Buyer Report' or name = 'Lost MA Upsell - Conveyancing' or name = 'Lost MA Upsell - Mortgage') ];
        for(easy_opportunity__c opp2 : opptys1)
        {
        oppstodelete2.add(opp2);
        }
        delete oppstodelete2;
Hi Team,

I have 2 custom fields Start Date and End date. I want to show an output where how many working days for each month do have for the given Start Date and End date. My formula gives only the No of total Business days  between Start Date and End Date. 

Ex: If Start Date= 01/20/2016  and End Date= 03/21/2017, it will give me total number of Busines days i.e 305.

However my requirment is to show Jan 2016 = 8,  Feb 2016 = 23, March 2016= 23..so on till End Date month....i.e March 2017= 15 business days. 

It should also consider the Leap year. 
Hi,
While checking the product duplicate i'm faceing Apex CPU Time out limit Exception.Here is the code
public list<BD_Identifier__c> LegacyproductBDlistinputcheck(list<BD_Identifier__c> bdlist)//bdllist contains list of products
    {
        set<string> dupcodeinput = new set<string>();
        system.debug('Class duplicate count:'+bdlist.size());//Size was 456 records
        for(BD_Identifier__c b: bdlist)
        {
            system.debug('Class duplicate:'+dupcodeinput.size());
            if (dupcodeinput.size()>0)
            {
                while (dupcodeinput.contains(b.SPM_BrokerDealer__C+b.SPM_Legacy_Product_Code__c))//After processing 64 records time out error was shown
                {
                    
                    if(b.SPM_BrokerDealer__c=='FSC')
                    {
                        string code =b.SPM_Legacy_Product_Code__c.right(1);
                        string productcode= b.SPM_Legacy_Product_Code__c;
                        if(code.isNumeric())
                        {
                            Integer i;
                            if(b.SPM_Legacy_Product_Code__c.right(2).isNumeric())
                            {
                                string s=b.SPM_Legacy_Product_Code__c.right(2);
                                Integer c,d;
                                c=Integer.valueOf(s.right(1));
                                d=Integer.valueOf(s.left(1));
                                if(d==c-1){
                                    code=b.SPM_Legacy_Product_Code__c.right(1); 
                                }
                                else{code=b.SPM_Legacy_Product_Code__c.right(2);}
                            }
                            i=Integer.valueOf(code)+1;
                            b.SPM_Legacy_Product_Code__c=((productcode+String.valueOf(i)).right(7));
                        }
                        else
                        {
                            b.SPM_Legacy_Product_Code__c=((productcode+String.valueOf(1)).right(7));
                        }
                    }
                    else if (b.SPM_BrokerDealer__c=='RAA' || b.SPM_BrokerDealer__c=='SPF' || b.SPM_BrokerDealer__c=='WFS')
                    {
                        string code =b.SPM_Legacy_Product_Code__c.right(1);
                        string productcode= b.SPM_Legacy_Product_Code__c;
                        if(code.isNumeric())
                        {
                            Integer i;
                            if(b.SPM_Legacy_Product_Code__c.right(2).isNumeric())
                            {
                                string s=b.SPM_Legacy_Product_Code__c.right(2);
                                integer c,d;
                                c=Integer.valueOf(s.right(1));
                                d=Integer.valueOf(s.left(1));
                                if(d==c-1){
                                    code=b.SPM_Legacy_Product_Code__c.right(1); 
                                }
                                else{code=b.SPM_Legacy_Product_Code__c.right(2);}
                            }
                            i=Integer.valueOf(code)+1;
                            b.SPM_Legacy_Product_Code__c=(b.SPM_Legacy_Sponsor_Code__c +(productcode+String.valueOf(i)).right(6));
                        }
                        else
                        {
                            b.SPM_Legacy_Product_Code__c=(b.SPM_Legacy_Sponsor_Code__c +(productcode+String.valueOf(1)).right(6));
                        }
                    }
                }
                dupcodeinput.add(b.SPM_BrokerDealer__C+b.SPM_Legacy_Product_Code__c);
            }
            else {dupcodeinput.add(b.SPM_BrokerDealer__C+b.SPM_Legacy_Product_Code__c);}
        }
        //system.debug('class remove duplicate'+bdlist);
        return bdlist;
    }
Hi everyone,
I would like to build a trigger that updates a custom field (a picklist) and chooses a specific item on the list, after I have sent an email. Because I am sending mails from Gmail and linking the service to Salesforce via the Ebsta app, the email appears only in "Activity History".
Since I am new to programming, I would greatly appreciate any help on how to write an apex trigger that updates the picklist field as soon as there is something in Lead "Activity History".
Thank you for your help!
Cheers, 
Lawrence
So I have a set of three visual force pages. Each is a pageblock table showing results from custom controller that is limiting based on parameters passed from commandlinks on the previous pages. One of the limiting parameters is a datetime, however when I pass the parameter to the controller it comes out as a string. Either I am converting this somewhere (can the list<object> handle datetime fields?) or the visualforce page is converting the datetime field to a string that looks like this:

Fri Nov 30 21:55:38 GMT 2012

And I need to either cast this back into a datetime variable or figure out how to pass it as a datetime. Any help that could be provided would be really appreciated! 

 Here is my controller:
 
public with sharing class attendance_class_joins {

    // an instance variable for the standard controller
    private ApexPages.StandardController controller {get; set;}
    // the object being referenced via url
    //private Lesson__c lesson {get; set;}
    // the variable getting set from the command button 
    public String className {get; set;}
    public String classTimeStr {get; set;}
    //public DateTime ClassTime {get; set;}
    
    
    //---------------------------------------------------------------------
    //Create list for student attendance of all active classes 
    //by using SOQL (seriously salesforce?) to generate list
    
    public ApexPages.StandardSetController activeclassList {
       get {
            if(activeclassList == null) {
                activeclassList = new ApexPages.StandardSetController(
                    Database.getQueryLocator([SELECT Name, Teacher__r.name 
                                              FROM Lesson__c 
                                              WHERE Inactive_lesson__c = False]));
            }
            return activeclassList;
        }
        set;
    }
    
    // Initialize setCon and return a list of records
    public List<Lesson__c> getActiveClasses() {
        return (List<Lesson__c>) activeClassList.getRecords();
    }
    
    
    // handle the action of the commandButton
    public PageReference processLinkClickSA() {
        System.debug('className: '+className);
        return page.lessonselection;
        //Now do something
    	 //go to page http://cs16.salesforce.com/apex/lessonselection
        //return null;
    }
    //------------------------------------------------------------------
    //Create the list for the lesson selection page.
    
    public ApexPages.StandardSetController classtimeList {
       get {
            if(classtimeList == null) {
                classtimeList = new ApexPages.StandardSetController(
                    Database.getQueryLocator([SELECT Name, Date_Time__c 
                                              FROM Lesson_Attendance__c 
                                              WHERE Lesson_ID__r.Name in (:className)
                                              AND Attendance__c = Null]));
            }
            return classtimeList;
        }
        set;
    }
    
    // Initialize setCon and return a list of records
    public List<Lesson_Attendance__c> getClassTimes() {
        return (List<Lesson_Attendance__c>) classtimeList.getRecords();
    }
    
    // handle the action of the commandButton
    public PageReference processLinkClickLS() {
        System.debug('className: '+className);
        //datetime classTime = DateTime.parse(classTimeStr);
        return page.takeroll;
    	 //Now do something
    	 //go to page http://cs16.salesforce.com/apex/lessonselection
        //return null;
    }
    
    //---------------------------------------------------------
    
    //serialize the date/time function gotten on the last page. 
    //datetime classTime = DateTime.parse(classTimeStr);
    //public DateTime classTimeStr() {
    //datetime classTime = ApexPages.currentPage().getParameters().get('classTimeStr');
    //return (DateTime)Json.deserialize(classTimeStr, DateTime.class);
	//}
    //Create the list for the take roll page
 	public ApexPages.StandardSetController rollcallList {
       get {
            if(rollcallList == null) {
                rollcallList = new ApexPages.StandardSetController(
                    Database.getQueryLocator([SELECT Student_ID__r.Name, Attendance__c, Notes__c 
                                              FROM Lesson_Attendance__c
                                              WHERE Lesson_ID__r.Name in (:className)]));
                                              	//AND Date_Time__c = :classTime]));
            }
            return rollcallList;
        }
        set;
    }
    
    // Initialize Roll call and return a list of records from the above query.
    public List<Lesson_Attendance__c> RollCall {get {
        return (List<Lesson_Attendance__c>) RollCallList.getRecords();
    }}
    
    //Custom save functionality.
    public PageReference save() {
        update RollCall;
        return page.Test_Page;
    }

}
And here are my visual force pages
 
<apex:page controller="attendance_class_joins">
  <h1>Student Attendance</h1>
  <h1>Student Attendance</h1>
  <body>This is where you can take roll and check students attendance records.</body>
  <body>Please select the class series you would like to take attendance for: </body>
      
      <apex:form >
     <apex:pageBlock title="List of Active Classes">
          <apex:pageBlockSection columns="1" >
              <apex:pageBlockTable value="{!ActiveClasses}" var="c">
                  <apex:column headerValue="Lesson Name">
                      <apex:outputText value="{!c.Name}"/>
                  </apex:column>
                  <apex:column headerValue="Teacher">
                      <apex:outputText value="{!c.Teacher__r.Name}"/>
                  </apex:column>
                  <apex:column headerValue="Choose Class">
                  	<apex:commandLink value="Next" action="{!processLinkClickSA}">
                        <apex:param name="classNameParam"
                                    value="{!c.Name}"
                                    assignTo="{!className}"/>
                  </apex:commandLink>
                  </apex:column>
                </apex:pageBlockTable>
          </apex:pageBlockSection>
      </apex:pageBlock>
    </apex:form>


</apex:page>




<apex:page controller="attendance_class_joins">
  <h1>Class Selection</h1>
  <body>Select the individual meeting of {!className} that you would like to take attendance for:</body>
      <apex:Form >
    	<apex:pageBlock title="List of {!className} Sessions">
          <apex:pageBlockSection columns="1" >
              <apex:pageBlockTable value="{!ClassTimes}" var="d">
                  <apex:column headerValue="Date/Time">
                      <apex:outputText value="{0,date,yyyy-MM-dd HH:mm:ss}">
                          <apex:param value="{!d.Date_Time__c}"/>
                          </apex:outputText>
                  </apex:column>
              		<apex:column headerValue="Choose Class">
                  		<apex:commandLink value="Next" action="{!processLinkClickLS}">
                        	<apex:param name="classTimeParam"
                                        value="{!d.Date_Time__c}"
                                		assignTo="{!classTimeStr}"/>
                  		</apex:commandLink>
                  	</apex:column>  
              </apex:pageBlockTable>
          </apex:pageBlockSection>
      </apex:pageBlock>
    </apex:Form>
</apex:page>


<apex:page controller="attendance_class_joins">
    <h1>
        Take roll call, select the correct attendance value from the dropdown for each student and add notes where appropriate. Then click save to commit.
    </h1>
    <apex:form >
        <apex:pageBlock title="Roll Call" >
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save"
                                    action="{!save}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockTable value="{!rollcall}" var="stud">
                <apex:column headerValue="Student">
                    <apex:outputText value="{!stud.Student_ID__r.Name}"/>
                </apex:column>
                <apex:column headerValue="Attended?">
                    <apex:inputField value="{!stud.Attendance__c}"/>
                </apex:column>
                <apex:column headerValue="Notes">
                    <apex:inputField value="{!stud.Notes__c}"/>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>




 
I am exporting data from one Salesforce org to another. I have come to tasks and for some reason I got stuck och mass emails. That is tasks that in the SF-GUI are present in the activity history of an object like contact or account for example. When I create a query via a data loader the tasks are not in scope. When I use the workbench and create a SOQL-query I cannot see these tasks. I know they are there but they don't show in any results.
For example use this SOQL-query in the workbench
select id,subject from Task where Subject like 'Mass%'
It gives me zero result.

A similar query gives me result as expected.
select id,subject from Task where Subject like 'Email%'

Now, why is that?

Thanks / Niklas
Hello All,

we send an email to salesforce with a content generated from a HTML form. The form includes content what website visitors can type in fields like "Firstname" "Lastname" etc.

A Salesforce Email Service (with an apex class) reads the content and saves it in the salesforce database. (Below is the code) 

The problem is that characters like "ä" are stored in salesforce like "�".

I tried already this before saving the content in the database: EncodingUtil.urlEncode(sBody, 'utf-8');

But it still dont work.

Many thanks in advance for your help!



 






global class EmailServiceKontact implements Messaging.InboundEmailHandler {
    // public static String emailFormat; 
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
        String emailSender = email.replyTo;
        String emailSub = email.subject;  
        
        // <Contact Start>
        String emailBody = email.htmlBody;




 
If you do not mind, can you please have a look at this issue?

My code is saving with no errors when saving so this is a runtime error, and I am executing in Anonymous Window the following:

AccountHandler.insertNewAccount(Acme Supply)

I am receiving the following error:
Line: 2, Column: 0  expecting a semi-colon, found '<EOF>'

There is not Line 2 in my code, and I do not know what to say about column 0.

Here is my code ( I am a newbie, trying to learn Apex)

public class AccountHandler {
    
       public static List<String> insertNewAccount(string nameAccount) {
       
                List<String> acctReturn = new List<String>();
           
       try {
                   Account acct = new Account(Name=nameAccount);    
                    insert acct;
                    System.debug(nameAccount);
           } 
        catch (DMLException e) 
               {
                   System.debug('A DML exception has occurred: ' + e.getMessage());
               }
        
        return acctReturn;
    
    }
}
I have a batch that's been running for years that started failing because of First error: Access to entity 'MatchingInformation' denied.  I've searched around and can't find anything about this and I can't find any object or class in salesforce called MatchingInformation.  It doesn't happen each time this batch runs, it seems to be arbitrary and can happen with any set of arguments.  The batch is below, simply it updates a list of records with a defined value.
 
global class util_sObjectFieldUpdaterBatch implements Database.Batchable<sobject>, Database.Stateful {

    /**
    Run This Batch

    string query = ;
    string nextBatch = ;
    string sObj = ;
    string field = ;
    object changeTo = ;
    integer batSize = ;
    
    ID idBatch = Database.executeBatch(new util_sObjectFieldUpdaterBatch(query,nextBatch,sObj,field,changeTo), batSize);
    **/

    global string query;
    global string nextBatch;

    global string sObjName;
    global string sObjFieldName;
    global sObjectType sObjType;
    global sObjectField sObjField;

    global object changeTo;

    private Map<String, Schema.SObjectType> smap = Schema.getGlobalDescribe();

    global integer NumBatches;
    
    global util_sObjectFieldUpdaterBatch(String qry, string nextBat, string obj, string field, object changeObj) {

        Query = qry;
        
        nextBatch = nextBat;

        sObjName = obj;
        
        changeTo = changeObj;

        SObjectType sObjType;

        if(smap.get(obj) != null){

            sObjType = smap.get(obj);

            Map<String,Schema.SObjectField> fieldMap = sObjType.getDescribe().fields.getMap(); 

            if(fieldMap.get(field) != null){
                
            	sObjFieldName = field;

            	sObjField = fieldMap.get(field);

            }

        }

    }
    
    global Database.QueryLocator start(Database.BatchableContext bcMain) {
        return Database.getQueryLocator(Query);
    }
    
    global void execute(Database.BatchableContext bcMain, List<sObject> scope) {

        for(sObject s : scope){
        	s.put(sObjField, changeTo);
        }

        if(scope.size() > 0) { 
            update scope; 
        }
    }
    
    global void finish(Database.BatchableContext bcMain) {

    } 
	
}

 
Hi Everbody,
I am new to apex, so please be patient. This is my first try at coding. Any help I could get is very much appreciated. I created a custom object (DataTable). This object does not have any parent/child relationships. I am trying to "copy" some information from Tasks into this custom object if the Task is related to an Opportunity. For now, all I want is to populate a field ( called TaskSubject__c) in my custom object that is equal to Subject on the Task/Activity object. Thank You! Here is what I got....

trigger AutoCreateDT on Task (after insert) {
for (Task t : Trigger.new) {
// Check if Task is related to Opportunity
if (t.what =='Opportunity') {
//Populate task subject in custom object called DataTable
DataTable d = new DataTable ();
d.TaskSubject__c = t.subject;

}
}
}
  • March 28, 2015
  • Like
  • 0
I created a VF page that renders as a 'pdf'. However when I test the VF page with a record, I return no results. I am not sure why.

VF PAGE
<apex:page standardController="Collateral_Development_Request__c" standardStylesheets="false" showHeader="false" sidebar="false" renderAS="pdf">
    <body>
        <apex:stylesheet value="{!URLFOR($Resource.styles, 'styles.css')}" />
        <center><apex:image value="{!URLFOR($Resource.QLogicLogos,'ultimate_logo_horiz_blue_on_white_small.jpg')}"/></center>
        <center><u>
            <apex:outputText value="{!$Organization.Street}" style="font-size:12px"/>&nbsp;&nbsp;&nbsp;&nbsp;
            <apex:outputText value="{!$Organization.City}, {!$Organization.State} {!$Organization.PostalCode}" style="font-size:12px"/>&nbsp;&nbsp;&nbsp;&nbsp;
            <apex:outputText value="{!$Organization.Phone}" style="font-size:12px"/> 
        </u></center>
       <br></br>
        <br></br><center><apex:outputText value="Approved Collateral Development Request" style="font-weight:bold; font-size:22px" /></center><br></br>
        <center><apex:outputText value="Collateral Development Request Detail" style="font-weight:bold; font-size:18px" /></center>
        <br></br><center><b>Approved Request Date:</b> <apex:outputText value="{!NOW()}" style="font-size:14px" /></center><br></br>
        <br></br><br></br>
        <apex:outputText id="name" value="Collateral Development Name: {!Collateral_Development_Request__c.Name}" /><br></br>
        <apex:outputText id="description" value="Collateral Request Description: {!Collateral_Development_Request__c.Collateral_Request_Description__c}" /><br></br>
        <apex:outputText id="status" value="Request Status: {!Collateral_Development_Request__c.Request_Status__c}"/><br></br>
        <apex:outputText id="priority" value="Priority Level: {!Collateral_Development_Request__c.Priority__c}"/><br></br>
        <apex:outputText id="projected" value="Projected Release Date: {!Collateral_Development_Request__c.Projected_Release_Date__c}" /><br></br>
        <apex:outputText id="actual" value="Actual Release Date: {!Collateral_Development_Request__c.Actual_Release_Date__c}" /><br></br>
        <apex:outputText id="theater" value="Theater: {!Collateral_Development_Request__c.Theater__c}" />
        <apex:outputText id="owner" value="Collateral Record Owner: {!Collateral_Development_Request__c.owner.name}" style="font-size:14px" /><br></br>
        <br></br>
        <br></br><center><apex:outputText value="Account Information" style="font-weight:bold; font-size:18px" /></center><br></br>
        <apex:outputText id="company" value="Company: {!Collateral_Development_Request__c.Account__r.name}" /><br></br>
        <apex:outputText id="category" value="Company Category Type: {!Collateral_Development_Request__c.Company_Category_Type__c}" /><br></br>
        <apex:outputText id="othercompanycategory" value="Other Company Category Type: {!Collateral_Development_Request__c.Company_Category_Type__c}"/>
        <apex:outputText id="audience" value="Audience Type: {!Collateral_Development_Request__c.Audience_Type__c}"/><br></br>
        <br></br>
        <br></br><center><apex:outputText value="Contact Information" style="font-weight:bold; font-size:18px" /></center><br></br>
        <br></br>
        <apex:outputText id="requester" value="Requester Name: {!Collateral_Development_Request__c.Requester_Name__c}" /><br></br>
        <apex:outputText id="email" value="Requester Email: {!Collateral_Development_Request__c.Requester_Email__c}" /><br></br>
        <apex:outputText id="phone" value="Requester Phone #: {!Collateral_Development_Request__c.Requester_Phone__c}"/><br></br>
        <br></br>
        <br></br><center><apex:outputText value="Collateral Development Information" style="font-weight:bold; font-size:18px" /></center><br></br>
        <br></br>
        <apex:outputText id="type" value="Collateral Type: {!Collateral_Development_Request__c.Collateral_Type__c}" /><br></br>
        <apex:outputText id="cycle" value="Sale Cycle: {!Collateral_Development_Request__c.Sale_Cycle__c}" /><br></br>
        <apex:outputText id="resource" value="Resource: {!Collateral_Development_Request__c.Resource__c}"/><br></br>
        <apex:outputText id="other" value="Other Resource: {!Collateral_Development_Request__c.Other_Resource__c}"/><br></br>
        <apex:outputText id="lead" value="Lead Gen Value: {!Collateral_Development_Request__c.Lead_Gen_Value__c}"/><br></br>
        <apex:outputText id="product" value="Product: {!Collateral_Development_Request__c.Product__c}" /><br></br>
        <apex:outputText id="location" value="Collateral Location: {!Collateral_Development_Request__c.Collateral_Location__c}" /><br></br>
        <apex:outputText id="collateral" value="Other Collateral Location: {!Collateral_Development_Request__c.Other_Location__c}"/><br></br>
        <apex:outputText id="application" value="Application Category: {!Collateral_Development_Request__c.Application_Category__c}"/><br></br>
        <apex:outputText id="solution" value="Application Solution: {!Collateral_Development_Request__c.Application_Solution__c}"/><br></br>
    </body>
    </apex:page> 
I have an email handler creating cases from a certain email coming in and they contain attachments.  If the attachment is in the body of the email the attachment works fine, but for some reason some of them come in a different way and the attachment is in an "attachment" section of the email and they get dropped off.  Is there something else I need to add to get these other attachments to add to the case?
  • March 20, 2014
  • Like
  • 0