• Greg Rohman
  • NEWBIE
  • 60 Points
  • Member since 2008
  • Vice President, Certified Salesforce Administrator
  • Advantage Group


  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 32
    Questions
  • 73
    Replies
I want to subtotal the number of documents on an invoice with the price per document, with the price being variable and in a picklist.  My simple mind thinks this simple formula would work:

Number_of_Documents__c * Document_Price__c

However, it seems that Salesforce can't compute formula this when one of the items is in picklist form.

First, why can Salesforce not compute such a simple formula when one of the values is from a picklist?

Second, what do I need to add to make this work?

The Number_of_Documents__c custom field is a number field.

The Document_Price__c is a picklist of numbers: 35, 25, 15, etc.

Finally, how do I express the Subtotal as a value in US dollars?
Hello.

I have a Visualforce component called "Rpt_MonthlyExpenseSummary_Excel" that outputs an Open Office XML file that opens properly in Excel with all formatting, formulas, named ranges and other items intact intact. When I embed this component on a simple page and access it via a browser, it prompts me to download the file, and everything functions properly. Here's a snippet of the VF page where I am including the component, and the XML contained in the downloaded file it generates:
 
<apex:page controller="CtrlRptMonthlyExpenseSummary" standardStylesheets="false" contenttype="application/vnd.ms-excel#TestExport_{!TODAY()}.xml">
    <c:Rpt_MonthlyExpenseSummary_Excel />
</apex:page>
Output:
<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel">
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
   <Alignment ss:Vertical="Bottom"></Alignment>
   <Borders></Borders>
   <Font ss:Color="#000000" ss:FontName="Calibri" ss:Size="12" x:Family="Swiss"></Font>
   <Interior></Interior>
   <NumberFormat></NumberFormat>
   <Protection></Protection>
  </Style>
  <Style ss:ID="sCurrency">
   <NumberFormat ss:Format="$#,##0"></NumberFormat>
   <Borders>
    <Border ss:LineStyle="Continuous" ss:Position="Bottom" ss:Weight="1"></Border>
    <Border ss:LineStyle="Continuous" ss:Position="Left" ss:Weight="1"></Border>
    <Border ss:LineStyle="Continuous" ss:Position="Right" ss:Weight="1"></Border>
    <Border ss:LineStyle="Continuous" ss:Position="Top" ss:Weight="1"></Border>
   </Borders>
  </Style>

I also attaching this same Excel file to an email template using <messaging.emailTemplate>:
 
<messaging:emailTemplate subject="Report: Monthly Expense Summary" recipientType="User">
    <messaging:htmlEmailBody >
            Omitted stuff here
    </messaging:htmlEmailBody>
    <messaging:attachment filename="Report: Monthly Expense Summary - {!MONTH(TODAY())}-{!YEAR(TODAY())}.xls" >
        <c:Rpt_MonthlyExpenseSummary_Excel />
    </messaging:attachment>
</messaging:emailTemplate>
The tempate functions correctly as well, and the attachment is included. The issue, though, is that portions of the XML file, namely the formatting and styles that I have defined, are being commented out with <!-- and //--> tags. Here's a relevant snippet of the attachment XML file:
<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel">
 <Styles>
  <Style ss:ID="Default" ss:Name="Normal">
<!--
   <Alignment ss:Vertical="Bottom"></Alignment>
   <Borders></Borders>
   <Font ss:Color="#000000" ss:FontName="Calibri" ss:Size="12" x:Family="Swiss"></Font>
   <Interior></Interior>
   <NumberFormat></NumberFormat>
   <Protection></Protection>
//-->
</Style>
  <Style ss:ID="sCurrency">
<!--
   <NumberFormat ss:Format="$#,##0"></NumberFormat>
   <Borders>
    <Border ss:LineStyle="Continuous" ss:Position="Bottom" ss:Weight="1"></Border>
    <Border ss:LineStyle="Continuous" ss:Position="Left" ss:Weight="1"></Border>
    <Border ss:LineStyle="Continuous" ss:Position="Right" ss:Weight="1"></Border>
    <Border ss:LineStyle="Continuous" ss:Position="Top" ss:Weight="1"></Border>
   </Borders>
//-->
</Style>

I cannot figure out why everything functions properly as a page, but when attached to an email, that portions of the XML file are being arbitrarily commented out. Any ideas? 

Much thanks in advance.

-Greg
Hello.

I have just come across the somewhat ridiculous convert-3mb-attachments-to-HTML limitation in Salesforce, which has effectively crippled a new app that I just developed.

The app is an expense app that permits users to enter expense details into a custom object, attach an image of a receipt (either via the desktop or mobile app), and then submit an expense report electronically that bundles all of the expense details into an email message with all of the receipts attached to the email. With this limitation, the attachments are all being sent as HTML files with links to the attachments, which appear to be hosted on some Salesforce instance that doesn't require a valid login to view.

I don't love the linking aspect, but I could live with it if there was a way to have the body of the email message contain links to the attachments, instead of each attachment being "attached" as an HTML file with an embedded link.

Here's a code snippet, just containing the code to add the attachments to an EmailFileAttachment. Everything above and below this code is functional and irrelevant to this issue.
        List<ContentVersion> attachmentData = new List<ContentVersion>();
        attachmentData = [SELECT ContentDocumentId,VersionData,FileExtension,FileType,Id,Title,PathOnClient FROM ContentVersion where Id IN :ContentVersionDetailsMap.keySet()];
        for (ContentVersion a :attachmentData) {
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
            efa.setContentType(extContentTypeMap.get(a.FileExtension)); // Content type of attachment
            efa.setFileName(a.Title + '.' + a.FileExtension); //Title of the PDF
            efa.setFileName(a.PathOnClient); //Title of the PDF
            efa.setBody(a.VersionData); //Body of the PDF,need to do transfer into blob
            fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);

Is there some way to include a list of the attachment links in the body of the message instead of actually attaching them as HTML files?
Thanks in advance.

-Greg
 
Hello.

Please see the greatly simplified code below. When I click the VF button that calls the "actionClassName" class, the ContentVersionDetailsMap variable is blank. I am looking for a way to obtain the contents of the ContentVersionDetailsMap variable in a method being called from a Visualforce actionbutton. Is this possible?

Thanks in advance.
public with sharing class CtrlClassName {

    public Map<Id,ContentVersion> ContentVersionDetailsMap = new Map<Id,ContentVersion>();

    public CtrlClassName() {
        Map<Id,ContentVersion> ContentVersionDetailsMap = new Map<Id,ContentVersion>([SELECT Id,Title,PathOnClient,VersionData,FileExtension FROM ContentVersion WHERE Id IN :contentDocIds]);
        system.debug('ContentVersionDetailsMap=' + ContentVersionDetailsMap);
    }

    public void actionClassName() {
        system.debug('ContentVersionDetailsMap=' + ContentVersionDetailsMap);
    }

}

 
Is there a way to use Design Tokens, either standard or custom, in SLDS Visualforce pages? All of the documentation I have seen refers to Lightning Components, but no mention of Visualforce pages that are using SLDS. If not, is it planned, and is there a recommended best practice for maintaining UI consistency, aside from a set of standard stylesheets in a static resource?

Thank you.

-Greg
Hello.

When syncing a contact from Outlook to Salesforce for an existing Account, is there a method to keep the Contact's address from Outlook on the Contact record? When I sync now, the address on the Salesforce Contact record is being overwritten by the address from the existing Salesforce Account.

Thank you in advance.

-Greg
Hello.

I'm using Dynamic SOQL to generate a dynamic query based on a field name that includes the year. For example, I have a field called "Sales_Goal_2014__c" on the User object, and will create subsequent fields for 2015 and so on. The Dynamic SOQL to obtain this value is functional, and is as follows:
// Determine the date for the snapshot (last day of previous month)
Date firstDayOfMonth = date.today().addMonths(-1).toStartOfMonth();
reportDate = firstDayOfMonth.addDays(Date.daysInMonth(firstDayOfMonth.year(), firstDayOfMonth.month()) - 1);
reportYear = reportDate.year();
String goalFieldName = 'Sales_Goal_' + string.valueOf(reportYear) + '__c';

String userQuery = 'SELECT Id,Name,' + goalFieldName + ' FROM User ORDER BY LastName ASC';
Map<Id,User> userMap = new Map<Id,User>((List<User>)Database.query(userQuery));
I now would like to loop on the collection of users and obtain the value of the dynamically-generated field name? I know the following code doesn't work, but it's pseudo-code for what I am looking to accomplish
for (User u : userMap.values()) {
	Decimal tempSalesGoal;
	tempSalesGoal = u.(goalFieldName);
	// rest of code here
}
Thanks in advance.

-Greg



Hello.

 

I'm attempting to create a permission set that would allow some One App-licensed users access to view all of my contacts. When attempting to set the "View All" object permission, though, I'm getting the following error:

 

Can't save permission set My_Set_Name_Here, which is assigned to a user with user license Force.com - One App. The user license doesn't allow the permission: Read All Contacts

 

Is there some way to permit one-app licenses to view all contacts in an org that has private contact sharing?

 

Thanks in advance.

 

-Greg

Hello.

 

I have a custom object, called "Deal__c", that has it's default sharing access set to private. I have a number of criteria-based sharing rules on that object, and they are properly sharing the records to the appropriate groups specified in the criteria sharing rules.

 

My problem lies when I query the "Deal__Share" object to programmatically obtain the groups that have been shared to via criteria sharing. In the code sample below, I'm querying the Deal__Share object for all of the sharing rules applied to a specific record. I'm using Workbench for this testing, but I'm getting identical results when querying through Apex:

 

SELECT AccessLevel,Id,ParentId,RowCause,UserOrGroupId FROM Deal__Share WHERE ParentId='<deal_id_here>'

This particular record has four shares returned: two are manual shares, and two criteria-based. For the two manual shares, the UserOrGroupId shows the correct user/group that has been shared to. But, for the two that are criteria-based, it's not showing the correct Id for the groups that have been shared via criteria sharing. In fact, I don't know what IDs it's returning, because when I attempt to view those Ids from within Salesforce, I'm returned an "Insufficient Priveleges" page. I'm logged in as the system administrator, so priveleges shouldn't be an issue.

 

Any insight or help is greatly appreciated. Thank you.

 

-Greg

 

 

 

Hello.

 

I've enabled Chatter in a sandbox org to do some testing, and am using Data Loader to import data. On a custom object, I've enabled Chatter feed tracking on some fields on that object. On any followed records, changes to any of those fields are showing up properly in my chatter feed. But, when I use data loader to import records into that object, changed fields are not being tracked via chatter.

 

Is there a setting, either in the org's setup or within Data Loader (command-line), that would enable feed tracking for bulk imports via Data Loader?

Thanks in advance.

 

-Greg

Hello.

 

I have a custom object called Expense that has a lookup field to the Contact object. I'm attempting to make a custom Visualforce edit page for the object, and I'd like to have the Contact field show up the same way it does on standard edit pages (ie with the autocomplete and the icon to click for a lookup).

 

I can't just use the standard controller for the Expense object, due to other logic I need in the controller, so I've created an extension. But, I cannot figure out how to get the contact field to show up. I had found some other references on the b boards to similar issues and have tried them (see the note about "phantom" record in the controller below), but have had no success.

 

My shortened page code is below:

 

<apex:page standardController="Expense__c" extensions="CtrlExpenseAddNew" >
	<apex:form >
		<apex:pageBlock title="Expense Edit" id="thePageBlock" mode="edit">
			<apex:pageMessages />
			<apex:pageBlockButtons >
				<apex:commandButton value="Save" action="{!saveExpense}"/>
			</apex:pageBlockButtons>
			<apex:pageBlockSection title="Expense Details" columns="2">
				<apex:pageBlockSectionItem >
					<apex:outputLabel for="expCategory" value="Category"/>
					<apex:selectList id="expCategory" value="{!expCategory}" size="1">
						<apex:selectOptions value="{!expCategoryOptions}"/>
					</apex:selectList>
				</apex:pageBlockSectionItem>
				<apex:pageBlockSectionItem >
					<apex:outputLabel for="expContact" value="Contact"/>
					<apex:inputField id="expContact" value="{!expContact.Id}"/>
				</apex:pageBlockSectionItem>
				<apex:pageBlockSectionItem >
					<apex:outputLabel for="expDescription" value="Description"/>
					<apex:inputText value="{!expDescription}"/>
				</apex:pageBlockSectionItem>
			</apex:pageBlockSection>
		</apex:pageBlock>
	</apex:form>
</apex:page>

 

My shortened controller code is below (unnecessary stuff removed for clarity):

 

public with sharing class CtrlExpenseAddNew {

  public String expType {get;set;}
  public String expDate {get;set;}
  public String expDescription {get;set;}
  public Decimal expMileage {get;set;}
  public String expCategory {get;set;}
  public String expAmex {get;set;}
  public Decimal expAmount{get;set;}
  public String expLocation {get;set;}
  public Contact expContact {get;set;}

	// populate the list of expense types
	public List<SelectOption> getExpTypeOptions() {
		// Obtain the picklist values for the Type__c field on the expense object
		Schema.DescribeFieldResult fieldResult = Expense__c.Type__c.getDescribe();
		List<Schema.PicklistEntry> picklistEntries = fieldResult.getPicklistValues();
		List<SelectOption> options = new List<SelectOption>();
       options.add(new SelectOption('',''));
		for (Schema.PicklistEntry entry : picklistEntries) {
		       options.add(new SelectOption(entry.getLabel(), entry.getValue()));
		}
		return options;
	}

	// populate the list of expense categories
	public List<SelectOption> getExpCategoryOptions() {
		// Obtain the picklist values for the Expense_Type__c field on the expense object
		Schema.DescribeFieldResult fieldResult = Expense__c.Expense_Type__c.getDescribe();
		List<Schema.PicklistEntry> picklistEntries = fieldResult.getPicklistValues();
		List<SelectOption> options = new List<SelectOption>();
       options.add(new SelectOption('',''));
		for (Schema.PicklistEntry entry : picklistEntries) {
		       options.add(new SelectOption(entry.getLabel(), entry.getValue()));
		}
		return options;
	}


    public CtrlExpenseAddNew(ApexPages.StandardController stdController) {

		// Read parameter values (if being created from an event or event/expense calendar)
		String paramDate = ApexPages.currentPage().getParameters().get('date'); 
		if (paramDate <> null) {expDate = paramDate;}

		String paramDesc = ApexPages.currentPage().getParameters().get('desc');
		if (paramDesc <> null) {expDescription = String.escapeSingleQuotes(paramDesc);}

		String paramType = ApexPages.currentPage().getParameters().get('type');
		if (paramType <> null) {expType = String.escapeSingleQuotes(paramType);}

		String paramCat = ApexPages.currentPage().getParameters().get('cat');
		if (paramCat <> null) {expCategory = String.escapeSingleQuotes(paramCat);}


		// Need to create "phantom" contact and lead objects for lookups to function properly
		// ref: http://boards.developerforce.com/t5/Visualforce-Development/lookup-inputField-causing-errors-w-standard-controller-extension/m-p/158894
		expContact = new Contact();

    }


  public pageReference saveExpense() {
    // Stuff removed
  }
}

 

Any assistance on this would be greatly appreciated. Thank you.

 

-Greg

 

Hello.

 

I have a page where I have multiple contacts being displayed via< apex:outputfield>. I've been directed to use outputfield because it includes the basic hover functionality for the record (based on the mini page layout), and that works well enough.

 

The problem is when there are several of the same contacts displayed on the same page. When there are more than one of the same record, the position of the hover details popup is always with the first occurence of the contact. My assumption is that has something to do with the GetHoverDetails function relying on the id of the contact, and when there are multiple instances of the same contact (and thus the same id on an <a> or <div> container), it chokes.

 

I've tried passing in a unique identifier from the controller to use as the ID for the outputfield, but the ID on outputfield has to be a literal value.

 

Any suggestions as to how to enable hover details for duplicate contacts on the same page? Thanks in advance.

 

-Greg

Hello.

 

I'm having trouble with a very simple VF page using the standard Contact controller. The code is below:

 

 

<apex:page standardController="Contact">
	<apex:form >
		<apex:detail subject="{!contact}" inlineEdit="true"/>
	</apex:form>
</apex:page>

When I inline edit a field and click the Save button, the buttons switch to "Saving..." and then the page just sits. It never refreshes. My complete VF page does contain additional code, but even when simplifying it to the simple code above, it still does not work. Inline editing works on the standard Contact page, which leads me to believe that it's not a trigger issue.

 

The identical code for the Account object, as seen below, works fine, leading me to believe it's not a browser issue (I've tested in Chrome, IE and Firefox):

 

<apex:page standardController="Account">
	<apex:form >
		<apex:detail subject="{!account}" inlineEdit="true"/>
	</apex:form>
</apex:page>

 

 

This appears to be bug, unless there's another explanation. Please advise. Thank you.

 

-Greg

 

 

Hello.

 

I'm looking for a way to customize the Account page to separate out Contacts based on the value of a field called "Inactive__c". Basically, I'd like to have all of the contacts with the value of the field as True in one list, and the value of the field False in another list.

 

I've created a custom page extension for Account,  I have the Apex code fully functional, and the custom lists are formatted and displaying properly on the VF page. My problem is getting the custom lists to appear between the account details and the rest of the related lists.

 

I could handle it like the following, where I'd have related lists turned off in the Detail section and then add them manually:

 

<apex:detail subject="{!Account}" relatedList="false"/>

<apex:pageBlock>Insert my custom lists here</apex:pageBlock>

<apex:relatedList list="Opportunities"/>
<apex:relatedList list="Expenses__r"/>

My problem with that, though, is that I have a number of different page layouts for the Account object, assigned to users in different roles. I'd much prefer to be able to use those page layouts to determine which related lists to display for each role, rather than having to do it with complex Apex.

 

Any suggestions or solutions would be greatly appreciated. Thank you.

 

-Greg


 

Hello.

 

Is there any documentation on how to properly mimic the default Salesforce look on dashboards in my visualforce dashboard components? I've tried including the standardStylesheets in my apex:page definition, and assigning the same classes to my output table/rows/columns, but that doesn't work. My assumption is that it's related to the iFrame that's used for using Visualforce on dashboards.

 

My code is below. It is close, but not exact. I've had to "fake" a couple of things to get it close. For example:

  • Created a div around everything with the "pbBody" class
  • Manually removed borders on each cell
  • Create individual styles for the "last" and "even " row styles

Is there a standard method of doing this?

 

 

<apex:page controller="CtrlDashAnnualClosedComp" showheader="false" sidebar="false" standardStylesheets="true">
    <apex:stylesheet value="/sCSS/Theme3/default/dashboard.css" />    
    <style type="text/css">
    .list tr.last td { border-bottom-width:0px;}
    .list tr.even td { background-color: #eeeeee;}
    </style>
    <div class="pbBody">
        <table class="list" border="0" cellspacing="0" cellpadding="0" width="100%">
            <tr class="headerRow">
                <th scope="col" style="border-width: 0px;">&nbsp;</th>
                <th scope="col" class="numericalColumn" style="border-width: 0px;">{!firstYear}</th>
                <th scope="col" class="numericalColumn" style="border-width: 0px;">{!secondYear}</th>
            </tr>
            <apex:repeat var="o" value="{!dashList}">
            <tr class="{!o.CSSclass}">
                <td style="border-width: 0px;"><span class="dashboardRowLabel">{!o.compMonth}</span></td>
                <td class="numericalColumn" style="border-width: 0px;"><span class="dashboardRowValue"><apex:outputText value="{0,number,currency}"><apex:param value="{!o.firstYearPrem}"/></apex:outputText></span></td>
                <td class="numericalColumn" style="border-width: 0px;"><span class="dashboardRowValue"><apex:outputText value="{0,number,currency}"><apex:param value="{!o.secondYearPrem}"/></apex:outputText></span></td>
            </tr>
            </apex:repeat>
        </table>
    </div>
</apex:page>

 

 

Thanks in advance.

 

-Greg

 

Hello.

 

On a page, I have an inputtext field called "giftItemCost". In the custom controller, I'm referencing that value directly in a SOQL query.

 

When I use the following, it works fine:

 

 

public decimal giftItemCost {get; set;}

 

However, in order to do unit testing (and thus assign a value to the inputtext during testing), I need an explicit getter and setter. So, when I switch it to the following, it doesn't work:

 

 

public decimal giftItemCost;
public decimal getGiftItemCost() { return giftItemCost; }
public void setGiftItemCost(Decimal d) { giftItemCost = d; }

Not only does it not work, but the button on the VF page stops working entirely. Oddly, my VF page has a series of other inputtext fields, and all of them are working properly using the latter explicit get/set version of the code.

 

Any explanation would be very appreciated. Thank you.

 

-Greg

 

 

 

Hello.

 

I was hoping someone could shed some light onto my problem. I have a Map that contains a String as the key, and a List of custom objects as the value, as follows:

 

private Map<String,List<Title_Deal__c>> mainUserDealMap = new Map<String,List<Title_Deal__c>>();

 I have some logic in my code where I'm looping on a list of users, and if certain criteria match, I'm adding the Title_Deal__c to the map, along with the user's first and last name as the key. The code is below:

 

 

        // Loop on each user
        for (user u: userListForWrapper) {
            // Clear variables
            groupIdTemp.clear();
            salespersonIdTemp.clear();
            dealIdTemp.clear();
            tempUserDealList.clear();

            // find all groups that each user belongs to, and store the group Id
            for (GroupMember gm: groupMemberListTemp) {
                if(gm.UserOrGroupId == u.Id) {
                    groupIdTemp.add(String.valueOf(gm.GroupId).substring(0,15));
                }
            }  
            //Determine which Salesperson__c contain that group ID, and store the salesperson Id
            for (Salesperson__C sp: salespersonListTemp) {
                if(groupIdTemp.contains(sp.Group_Id__c)) {
                    salespersonIdTemp.Add(sp.Id);
                }
            }

            // Loop on deals
            for (Title_Deal__c deal: dealListTemp) {
                if(salespersonIdTemp.contains(deal.Salesperson__c)) {
                    // Add the deal to a temp list, to be added to the main salesperson/deal map
                    tempUserDealList.Add(deal);
                }
            }

    
            // Add the list of deals to the main salesperson/deal map, with the name as the key
            string tempName = u.FirstName + ' ' + u.LastName;
            mainUserDealMap.put(tempName,tempUserDealList);

            system.debug('tempname=' + tempName + ', deals=' + tempUserDealList);
            system.debug('map=' + mainUserDealMap.get(tempName));
        }

 

 

Everything up to that point works fine. When I view the system log output from the two debug statements at the end, they match, as they should.

 

The problem is when I do anything with the map outside of the user loop. I add the following line (where "John Doe" is a valid key name) just outside of the user loop:

 

 

        system.debug('testmap2=' + mainUserDealMap.get('John Doe'));

 

Instead of returning the actual list of Title_Deal__c records that are actually assigned to the "John Doe" key, it's returning one of the other lists, assigned to another key. It appears that it returns the List from the last item entered into the Map, as opposed to the List at the key I've requested.

 

 

Any guidance or assistance would be greatly appreciated. Thank you in advance.

 

-Greg

 

 

Hello.

 

I've attemped the following logic numerous times (as a trigger, trigger calling apex, batchable, @future) and every attempt I've run into governor limits. I'm not sure how to achieve what I'm looking to do.

 

Basically, I have a custom object called Gift, that contains a lookup to Account. The Account object has a string field called TAGS_Applic_Codes that contains a 5-character unique identifier to a legacy system. In our legacy system, though, it's possible for a single account to have multiple codes (different addresses, for example, will each have their own code, and thus be a separate Account record in Salesforce). As such, the Account object also contains a string field called Related_TAGS_App_Codes that contains a comma delimited listing of all of the TAGS applic codes that should be treated together.

 

The Gift object contains a currency field called Total_Cost, and the Account object contains a field called X2010_Gift_Expenditure_Total. What I'm looking to accomplish is that whenever a gift record is created, I want to calculate the total of all of the gifts for that particular Account AND any related accounts through that additional field, and store them in the X2010_Gift_Expenditure_Total field on the Account object (and related records).

 

Below is a semi-functional Trigger version of my code, so you can see my thought process. In this particular version, I'm getting a "too many query rows" error, but my governor errors have ranged from that, to "too many SOQL queries: 21", to limits on batchables and @future calls.

 

 

 

trigger trigUpdateCompanyGiftTotal on Gift__c (after insert, after update, after delete) {


List<Id> changedAccountIds = new List<Id>();
List<Account> changedAccounts = new List<Account>();
List<Account> allAccounts = new List<Account>();
List<Gift__c> allGifts = new List<Gift__c>();
Map<Id,Account> linkedAccounts = new Map<Id,Account>();

// Store all accounts and gifts to avoid governor limits
for (Account acc: [SELECT id, name FROM account]) {
allAccounts.add(acc);
}
allGifts = [SELECT Id FROM Gift__c];


//Loop on each changed gift entry. For deletes, need trigger.old
if (Trigger.isDelete) {
for(Gift__c g : Trigger.old){
if (g.Company_Firm__c <> Null) {
changedAccountIds.add(g.Company_Firm__c);
}
}
} else {
for(Gift__c g : Trigger.new){
changedAccountIds.add(g.Company_Firm__c);
}
}


// In triggers, lookup fields do not contain references to the entire object... they only contain the Id.
// So, need to get the actual changed Account objects from the stored IDs.
for (Id changedId: changedAccountIds) {
changedAccounts = [SELECT Id,Related_TAGS_App_Codes__c FROM Account WHERE Id=:changedId];
}

for (Account a: changedAccounts) {
//Determine if any related accounts by a nested loop over the full account list
if (a.Related_TAGS_App_Codes__c <> null && a.Related_TAGS_App_Codes__c.length() > 0) {
for (Account accLinkCheck: allAccounts) {
if (a.Related_TAGS_App_Codes__c.contains(accLinkCheck.Tags_Applic__c)) {
linkedAccounts.put(a.Id,accLinkCheck);
}
}
} else {
linkedAccounts.put(a.Id,a);
}
}


// Loop on all gifts, adding the totals and storing it back in the account and any related accounts
Decimal totalGift2009 = 0;
Decimal totalGift2010 = 0;

for (Gift__c g: allGifts) {
if (linkedAccounts.containsKey(g.Company_Firm__c)) {
if (g.Date__c.year() == 2009) {
totalGift2009 = totalGift2009 + g.Total_Cost__c;
}
if (g.Date__c.year() == 2010) {
totalGift2010 = totalGift2010 + g.Total_Cost__c;
}
}
}


// Update the total for each account
for (Account acc: linkedAccounts.values()) {
acc.X2009_Gift_Expenditure_Total__c = totalGift2009;
acc.X2010_Gift_Expenditure_Total__c = totalGift2010;
update acc;
}

}

 

My last resort would be to eliminate the trigger portion of this and just have a batch process that runs the update at set intervals, but I'd really prefer to avoid that and have it update when a Gift record is added/changed. I just don't see a way to do it without hitting some sort of governor limit.

 

Any advice is greatly appreciated. Thank you.

 

 

-Greg

Hello.

 

I have an apex class on sandbox, with 100% unit test coverage, that I recently modified and am attempting to deploy to production via ANT. When I attempt to deploy this single class, though, I'm getting 0% unit test failures on EVERY one of my existing triggers on production. The existing triggers all have 100% coverage.

 

I tried deploying it via the "Deploy" option under "Setup" and that worked successfully. What would cause the ANT deployment to fail (after having worked for many months) but the Deploy option to succeed?

 

Thanks in advance.

 

-Greg

Hello.

 

I'm building a simple system to look for similar last names in Leads and Contacts. Basically, I want to retrieve a list of all of our Leads, and for each Lead, see a list of Contacts with similar last names.

 

My theoretical approach is to first create lists of all of the prospects and contacts:

// Get all active prospects
SoqlQueryString = 'SELECT Name,LastName,Company,Owner.Name,Status,LastActivityDate FROM Lead WHERE IsConverted=false ORDER BY LastName';
ProspectResults = Database.query(SoqlQueryString);

// Get all contacts
SoqlQueryString = 'SELECT Name,LastName,Account.Name,Salesperson__c,Type__c FROM Contact ORDER BY LastName';
ContactResults = Database.query(SoqlQueryString);

 I'd then iterate over both lists, to find the count of potential matches for each prospect (to display on theVForce page, along with each prospect):

 

 

// Iterate over each prospect, checking all of the contacts for similar last names
for (Lead pr:ProspectResults) {
Integer intCount = 0;
for (Contact cr:ContactResults) {

if (cr.LastName == pr.LastName) {
intCount += 1;
mapContactCount.put(cr.Id,intCount);
}

}
}

 

 Here's where I'm stumped. As I said, on my page, I'd like to display a list of the Leads, along with the count of how many potential matches. I'd then like to display those potential contact matches either automatically or via click (AJAX). I'll try to illustrate below:

 

 

  • Joe Smith (2 matches) click to view matches
    • Joe Smith
    • Mike Smith
  • Steve Jones (0 matches)
  • John Doe (1 match) click to view matches
    • Jane Doe



The "click to view matches" could either programmatically show the Contact list underneath the Prospect (via AJAX), or the Contact lists could always be displayed (although the page would get very long). I'd prefer the former.


On the VF page, I've gotten to the point of being able to display the list of Prospects, but have no idea how to display the count, and then not a clue as to how to then go about displaying the potential Contact matches. I imagine it would involve passing each of the Prospect ID back to an APEX function that returns the Contacts, but not sure how to implement that.

 

 

 

 

 Any help or starting point is greatly appreciated. Thanks.

 

-Greg

 

Hello.

 

In Summary reports, if you attempt to drill down to a field that contains an ampersand (&) character, the report filter incorrectly escapes out the ampersand to "&amp;" and the resulting drilled-down report is blank.

 

For example. I have a summary report, with an account name "Acme & Co." If I check that account on the report and drill down, the resulting report is blank, because the Filtered By says "Acme &amp; Co." I then manually have to edit the filtering to remove the "amp;" to make it work.

 

This seems like a bug. Please advise. Thanks.

 

-Greg

Hello.

 

In Summary reports, if you attempt to drill down to a field that contains an ampersand (&) character, the report filter incorrectly escapes out the ampersand to "&amp;" and the resulting drilled-down report is blank.

 

For example. I have a summary report, with an account name "Acme & Co." If I check that account on the report and drill down, the resulting report is blank, because the Filtered By says "Acme &amp; Co." I then manually have to edit the filtering to remove the "amp;" to make it work.

 

This seems like a bug. Please advise. Thanks.

 

-Greg

Hello.

I have just come across the somewhat ridiculous convert-3mb-attachments-to-HTML limitation in Salesforce, which has effectively crippled a new app that I just developed.

The app is an expense app that permits users to enter expense details into a custom object, attach an image of a receipt (either via the desktop or mobile app), and then submit an expense report electronically that bundles all of the expense details into an email message with all of the receipts attached to the email. With this limitation, the attachments are all being sent as HTML files with links to the attachments, which appear to be hosted on some Salesforce instance that doesn't require a valid login to view.

I don't love the linking aspect, but I could live with it if there was a way to have the body of the email message contain links to the attachments, instead of each attachment being "attached" as an HTML file with an embedded link.

Here's a code snippet, just containing the code to add the attachments to an EmailFileAttachment. Everything above and below this code is functional and irrelevant to this issue.
        List<ContentVersion> attachmentData = new List<ContentVersion>();
        attachmentData = [SELECT ContentDocumentId,VersionData,FileExtension,FileType,Id,Title,PathOnClient FROM ContentVersion where Id IN :ContentVersionDetailsMap.keySet()];
        for (ContentVersion a :attachmentData) {
            Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment();
            efa.setContentType(extContentTypeMap.get(a.FileExtension)); // Content type of attachment
            efa.setFileName(a.Title + '.' + a.FileExtension); //Title of the PDF
            efa.setFileName(a.PathOnClient); //Title of the PDF
            efa.setBody(a.VersionData); //Body of the PDF,need to do transfer into blob
            fileAttachments.add(efa);
        }
        mail.setFileAttachments(fileAttachments);

Is there some way to include a list of the attachment links in the body of the message instead of actually attaching them as HTML files?
Thanks in advance.

-Greg
 
Hello.

Please see the greatly simplified code below. When I click the VF button that calls the "actionClassName" class, the ContentVersionDetailsMap variable is blank. I am looking for a way to obtain the contents of the ContentVersionDetailsMap variable in a method being called from a Visualforce actionbutton. Is this possible?

Thanks in advance.
public with sharing class CtrlClassName {

    public Map<Id,ContentVersion> ContentVersionDetailsMap = new Map<Id,ContentVersion>();

    public CtrlClassName() {
        Map<Id,ContentVersion> ContentVersionDetailsMap = new Map<Id,ContentVersion>([SELECT Id,Title,PathOnClient,VersionData,FileExtension FROM ContentVersion WHERE Id IN :contentDocIds]);
        system.debug('ContentVersionDetailsMap=' + ContentVersionDetailsMap);
    }

    public void actionClassName() {
        system.debug('ContentVersionDetailsMap=' + ContentVersionDetailsMap);
    }

}

 
I'm using the Salesforce REST APIs to created customers (in our case organizations) that can have n-number of agents (users within an organization). Most of them only have 1-2 users, but currently, I have an agent rich text field where I just append every agent with line breaks in between each name because I didn't know a way accomodate for what I was needing. In other words, I would have to create n-number of fields within salesforce, each with a unique field name. Is there a better way to do this?
I'm looking to recreate, in Salesforce, a form that some of our officers use for processing payments.  The part of the form called "Amount Due" requires several formulas, which I'm not sure how to create.  As I'm new to Salesforce and creating formulas, any help would be appreciated!

The form looks like this, with the items in bold (Previous Balance, Credit,Total Due, and Remaining Balance) representing what I need to figure out formulas for:

Subtotal: (Greg Rohman helped me with this, and is an amount calculated, in US dollars, by multiplying # of documents by price per document)

Delivery Charges: (This is a flat fee and is therefore a picklist for either 0 or $15)

Previous Balance: (= Remaining Balance, if positive, from the last time this company did business with us)

Credit: (= Remaining Balance, if negative, from the last time this company did business with us)

Total Due: (= Subtotal + Delivery Charges + Previous Balance - Credit)

Total Paid: (This is manually enterered by our officers, in dollars)

Remaining Balance: (= Total Due - Total Paid; if positive, this becomes the new Previous Balance for the company on their next invoice; if negative, this becomes the new credit for the company on their next invoice)

Would you have any ideas about how to do this?
I want to subtotal the number of documents on an invoice with the price per document, with the price being variable and in a picklist.  My simple mind thinks this simple formula would work:

Number_of_Documents__c * Document_Price__c

However, it seems that Salesforce can't compute formula this when one of the items is in picklist form.

First, why can Salesforce not compute such a simple formula when one of the values is from a picklist?

Second, what do I need to add to make this work?

The Number_of_Documents__c custom field is a number field.

The Document_Price__c is a picklist of numbers: 35, 25, 15, etc.

Finally, how do I express the Subtotal as a value in US dollars?
Hello.

When syncing a contact from Outlook to Salesforce for an existing Account, is there a method to keep the Contact's address from Outlook on the Contact record? When I sync now, the address on the Salesforce Contact record is being overwritten by the address from the existing Salesforce Account.

Thank you in advance.

-Greg
Hello.

I'm using Dynamic SOQL to generate a dynamic query based on a field name that includes the year. For example, I have a field called "Sales_Goal_2014__c" on the User object, and will create subsequent fields for 2015 and so on. The Dynamic SOQL to obtain this value is functional, and is as follows:
// Determine the date for the snapshot (last day of previous month)
Date firstDayOfMonth = date.today().addMonths(-1).toStartOfMonth();
reportDate = firstDayOfMonth.addDays(Date.daysInMonth(firstDayOfMonth.year(), firstDayOfMonth.month()) - 1);
reportYear = reportDate.year();
String goalFieldName = 'Sales_Goal_' + string.valueOf(reportYear) + '__c';

String userQuery = 'SELECT Id,Name,' + goalFieldName + ' FROM User ORDER BY LastName ASC';
Map<Id,User> userMap = new Map<Id,User>((List<User>)Database.query(userQuery));
I now would like to loop on the collection of users and obtain the value of the dynamically-generated field name? I know the following code doesn't work, but it's pseudo-code for what I am looking to accomplish
for (User u : userMap.values()) {
	Decimal tempSalesGoal;
	tempSalesGoal = u.(goalFieldName);
	// rest of code here
}
Thanks in advance.

-Greg



Hello.

 

I have a custom object, called "Deal__c", that has it's default sharing access set to private. I have a number of criteria-based sharing rules on that object, and they are properly sharing the records to the appropriate groups specified in the criteria sharing rules.

 

My problem lies when I query the "Deal__Share" object to programmatically obtain the groups that have been shared to via criteria sharing. In the code sample below, I'm querying the Deal__Share object for all of the sharing rules applied to a specific record. I'm using Workbench for this testing, but I'm getting identical results when querying through Apex:

 

SELECT AccessLevel,Id,ParentId,RowCause,UserOrGroupId FROM Deal__Share WHERE ParentId='<deal_id_here>'

This particular record has four shares returned: two are manual shares, and two criteria-based. For the two manual shares, the UserOrGroupId shows the correct user/group that has been shared to. But, for the two that are criteria-based, it's not showing the correct Id for the groups that have been shared via criteria sharing. In fact, I don't know what IDs it's returning, because when I attempt to view those Ids from within Salesforce, I'm returned an "Insufficient Priveleges" page. I'm logged in as the system administrator, so priveleges shouldn't be an issue.

 

Any insight or help is greatly appreciated. Thank you.

 

-Greg

 

 

 

Is it possible to access the overall backend database of standard objects of an organization from apex class?If possible,explain me with an example.

 

For your kind information i am using developer edition in force platform.

 

Its urgent.Please help me.

 

Regards,

S.Sivakumar

Hi i have created a one visual force page whic is rendering as PDF.

In this one table is rendering dynamicaly(not a apextable). I want to show table row in alterante color. i found some line of code which used JQuery, this works fine when i render as html but now when , i render it as 'PDF'

 

$(document).ready( function(){

$("#myTable tbody tr:visible:even",this).css('background-color','#fffffe');
$("#myTable tbody tr:visible:odd",this).css('background-color','#e0dfde');
}
)

 

Please tell solution ASAP.

Hello.

 

I've enabled Chatter in a sandbox org to do some testing, and am using Data Loader to import data. On a custom object, I've enabled Chatter feed tracking on some fields on that object. On any followed records, changes to any of those fields are showing up properly in my chatter feed. But, when I use data loader to import records into that object, changed fields are not being tracked via chatter.

 

Is there a setting, either in the org's setup or within Data Loader (command-line), that would enable feed tracking for bulk imports via Data Loader?

Thanks in advance.

 

-Greg

Hi Everyone,

 

I've run into an 'out of the box' problem that I could do with someone advice solving.

 

 

The situation

There's a third party system that inserts new order records (custom object) into salesforce through the API. The third party system may or may not insert one or more payment instruction records (a master-detail object of order) 90 seconds after the order is inserted. I've been asked to make a PDF order confirmation that gets emailed to the customer automatically when one of these orders is received.

 

The problem

The confirmation email needs to include payment instructions that we've received, but orders don't require payment instructions. Sometimes we get orders with no instructions initially. We might get those instructions much later on, but we still need to send a confirmation. This has two implications:

 

  1. I can't trigger this email from the order object because we haven't got the payment instructions by then so all confirmations will appear as if we haven't received the instructions.
  2. I can't trigger this email from the payment instruction object because if an order doesn't have payment instructions, we won't send a confirmation at all.

A failed solution

I thought I'd be smart and set up a scheduled apex task that runs every 5 minutes, and collects all orders, older than three minutes that haven't had a confirmation sent (using a checkbox to indicate whether the confirmation has been sent or not). This sounded like a decent hack on paper, but then I found out you can't send emails from scheduled apex. This fact alone has thrown my only remaining option on the fire.

 

 

Are there any ideas out there on how I could solve this problem?