• JNic
  • NEWBIE
  • 230 Points
  • Member since 2008

  • Chatter
    Feed
  • 9
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 83
    Questions
  • 109
    Replies

Hi,

 

I have an apex trigger on Case object that is supposed to automatically associate Cases to Contact records based on the AccountId field and its properties.

My trigger works well when I update existing Cases, but it throws the "attempt to de-reference a null object" error whenever I create a new Case.

 

This trigger first looks at the Email__c field set on the Account associated (Case.Account.Email__c) and tries to find existing contacts with that email address. If it didn't find a contact with that email address, it creates a Contact with some account info and associates it with the Case accordingly. If it did find contacts with that email address, it will query for them and associate them with the Case.

 

Here is my code (the line causing the error is highlighted in red):

 

trigger caseNSFBefore on Case (before insert, before update) {
    List<String> emailAddresses = new List<String>();
    List<String> accountIds = new List<String>();
    //First exclude any cases where the contact is set
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null &&
            caseObj.AccountId != null)
        {
            accountIds.add(caseObj.AccountId);
            System.debug('AccountEmail*********' + accountIds);
            List<Account> listAccounts = [Select Id,Email__c, firstName__c, lastName__c, primePhone__c From Account Where Id in :accountIds];
            for (Account a :listAccounts){
            emailAddresses.add(a.Email__c);
            System.debug('AccountEmail*********' + emailAddresses);
            }

        }
    }
    //fetch all the Account records from database
    Map<Id, Account> mapAccounts = new Map<Id, Account>([Select Id, Email__c, firstName__c, lastName__c, primePhone__c From Account Where Id in :accountIds]);

    //Now we have a nice list of all the email addresses.  Let's query on it and see how many contacts already exist.
    List<Contact> listContacts = [Select Id,Email From Contact Where Email in :emailAddresses];
    Set<String> takenEmails = new Set<String>();
    for (Contact c:listContacts) {
        takenEmails.add(c.Email);
    }
    
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();
    List<Case> casesToUpdate1 = new List<Case>();



    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null &&
            caseObj.AccountId !=null &&
           !takenEmails.contains(mapAccounts.get(caseObj.AccountId).Email__c))
        {
                List<Account> listAccounts = [Select Id,Email__c, firstName__c, lastName__c, primePhone__c From Account Where Id in :accountIds];
                for (Account a :listAccounts){
                    
                Contact cont = new Contact(FirstName= a.firstName__c,
                                            LastName= a.lastName__c,
                                            AccountId = a.Id,
                                            Phone = a.primePhone__c,
                                            Email= a.Email__c);
                emailToContactMap.put(mapAccounts.get(caseObj.AccountId).Email__c,cont);
                casesToUpdate.add(caseObj);
                
                }
        } else {
        casesToUpdate1.add(caseObj);    
        }
    }
    
    List<Contact> newContacts = emailToContactMap.values();
    insert newContacts;
    
    for (Case caseObj:casesToUpdate) {
        Contact newContact = emailToContactMap.get(mapAccounts.get(caseObj.AccountId).Email__c);
        
        caseObj.ContactId = newContact.Id;
    }
        for (Case caseObj:casesToUpdate1) {
        Contact existingContact = [select id from Contact where Email = :mapAccounts.get(caseObj.AccountId).Email__c  limit 1];        
        caseObj.ContactId = existingContact.Id;
    }
}

 

 

I would appreciate your help.

 

 

Thanks,

 

  • November 09, 2012
  • Like
  • 0

All,

 

 

Does anyone know what happens if your run out of storage capacity in your org?

Will your org stop working? Will your users be prompted with errors when they attempt to create records?

 

Any information is appreciated.

 

 

Thanks,

 

 

  • October 29, 2012
  • Like
  • 0

Hi all,

 

I have a scheduled report that needs to go out via email at 9:30 am every morning - not 9 or 10 (it's currently set to run at 10:00 am which is too late).

 

I understand the reporting limitations and I beleive reports can be scheduled to run every hour. More details can be found here: http://www.salesforce.com/us/developer/docs/packagingGuide/Content/dev_package_limits_for_pe_ge.htm.

 


What is the best practice when it comes to building such custom scheduled reports that can meet above requirement (AKA Runtime of every half  hour)?

 

Ideally, I would like such capability to be offered through the out-of-the-box features.

 

 

Kindly provide youre comments.

 

 

Regards,

 

  • October 22, 2012
  • Like
  • 0

All,

 

I have the Inline Editing enabled in my org and it works fine for my Opportunity object.

But I cannot beneft from this feature on some of the other standard objects such as Contacts, Accounts, and Cases.

 

I beleive this feature is available for all objects but for some reason I cannot seem to have it.

 

Please help.

 

Thanks,

 

 

  • August 29, 2012
  • Like
  • 0

Hi all,

 

I have a JavaScript List button that I want to use in Contacts related list of Account object. This button is supposed to grab and alert the user with Email addresses of contacts selected.

My code works whenever a signle record is selected, but it throws a "INVALID_QUERY_FILTER_OPERATOR" whenever multiple contact records are selected.

 

Need help pls.

 

{!RequireScript("/soap/ajax/20.0/connection.js")}

var contactRecords= {!GETRECORDIDS($ObjectType.Contact)};
var contactEmails = " ";

var ccEmails = "p4=salesforce@tionetworks.com&";

if (contactRecords.length ==0) {
alert("Please select at least one Contact record.");
} else {


var result = sforce.connection.query("select Name, Id, Email from Contact Where Id ='" +contactRecords+ "'");
var records = result.getArray("records");

for (var i=0; i< records.length; i++) {
var email = records[i].Email;
}
contactEmails += email;
alert("records:"+contactEmails);
}

 

Any help is appreciated.

 

 

Thank you,

 

 

Behzad

  • August 16, 2012
  • Like
  • 0

Hi all,

 

I have a visualforce page that summarizes details of an SOW.

I want to render this page as pdf, so I used rendered="pdf" in my page component.

 

This page works fine, but at the end of my page there some bogus information:

JanuaryFebruaryMarchAprilMayJuneJulyAugustSeptemberOctoberNovemberDecember
2010201120122013201420152016
SunMonTueWedThuFriSat
Today

 

I don't understand where above content comes from. I need to get rid of it somehow.

 

Any ideas?

 

Thanks,

  • October 25, 2011
  • Like
  • 0

Hey guys,

 

Contacts are a child of a Lead, so a Lead can have multiple contacts (Contacts >> Lead). Once the user converts the lead, I want to associate all of the child Contacts with the converted Account. I have a trigger as follows:

trigger leadAfter on Lead (after update) {

    //create a list of Contacts to update with Converted Account ID
    List< Contact > contacts = new list< Contact >();
   
  for ( Lead l : Trigger.new )
  {
    if (Trigger.old[0].isConverted == false && Trigger.new[0].isConverted == true) {
        System.debug('******Entering LeadAfter******');

        //Create a list of contacts that matches the Converted LeadId
        Contact c = [SELECT id, Lead__c, Name, AccountId FROM Contact c WHERE c.Lead__c = :l.Id AND c.AccountId = null];
       
        c.AccountId = l.ConvertedAccountId;
        contacts.add(c);
    }
        update contacts;
}
}

 

This trigger doesn't work and throws the following error: List has more than 1 row for assignment to SObject Trigger.leadAfter: line 12, column 21.

 

How can I update all of the child Contacts in a bulk manner?

 

Your input is appreciated.

 

  • July 22, 2011
  • Like
  • 0
Hi all, I have a controller that it's supposed to parse Subject line of an Email and extract a certain set of stings. For example, If the Subject line is [112233-notification number 22] - [Customer Support], I want to be able to extract only the "112233" portion of the text. I use the code below to find the index of "[" & index of last "-". String extract = c.Subject.substring(c.Subject.indexOf('[')+1, c.Subject.LastIndexOf('-')); However, I received "112233-notification number 22]" as my extract string. How should I go about locating only the "112233" part? My method needs to smart enough to locate only the integer between [ & - (within the closed [ ]). Appreciate your inputs.
  • June 06, 2011
  • Like
  • 0

Hi all,

 

I'm building an EmailMessage Trigger that is supposed to identify a case that was created by Email-To-Case feature and update a custom field called SuppliedToEmail__c with the ToAddress of the Email that has been invoked in this trigger.

 

My After Update is below:

trigger EmailMessageAfterUpdate on EmailMessage (After update) {
    for (EmailMessage newEmail : trigger.new){
    System.debug('******Entering EmailAfterUpdate******');

        if(Trigger.oldMap.get(newEmail.id).ParentId == null && newEmail.ParentId != null){
        Case c = [SELECT id, SuppliedToEmail__c FROM Case WHERE Id = :newEmail.ParentId];
            System.debug('******Entering EmailAfterUpdate\n'+c.CaseNumber+'******');
        c.SuppliedToEmail__c = newEmail.ToAddress;
        update c;
            System.debug('******Entering EmailAfterUpdate\n'+c.SuppliedToEmail__c+'******');
        }
    }
}

 

Unfortunately this trigger is not being invoked, I confirmed by ranning some tests and reviewing the debug logs.

 

I want to replicate the WebEmail (SuppliedEmail) field update, upon creation of a Email-to-Case record, to perform the same thing with my custom email field.

 

Your help is appreciated.

 

  • June 01, 2011
  • Like
  • 0

Hey all,

 

Our org uses a number of Email-to-Case processes, and we want to identify the ToAddresses used for the generated cases to leverage the workflow capacities. We are designing a IsInsert trigger that will automatically populate a custom field with the value of the ToAddress used.

 

The idea is very similar to the Web Email (SuppliedEmail) default page that associates a case with a originator's email address. In this trigger, we are doing a query for the originator's emailmessage and its information.

 

I'm not sure how to do the following:

1) Locate the email message that created the case. Would the code below locate the email that I'm loolking for?

         list<EmailMessage> email = [
         select
         id, ParentId, ToAddress
         from EmailMessage
         where ParentId = c.id  Limit 1];

2) Locate the ToAddress field. ToAddress in above query should be the Email-to-Case address for the created case c. Is that correct?

 

 

Thanks,

 

  • May 29, 2011
  • Like
  • 0
Hey guys, Can you provide a hyperlink or a link to a URL through a Error message displayed as part of a Trigger? For example, instead of hardcoding the URL as shown below, use a markup to make it a link: c.addError('ERROR TRM100: There is already an identical record: Record Number '+cs.Number+' (https://na8.salesforce.com/'+cs.Id+')'); This currently reads as: Error: Invalid Data. Review all error messages below to correct your data. ERROR TRM100: There is already an identical record: Record Number 60311 (https://na8.salesforce.com/500M0000000mJJ9IAM) It would be great if I could make the "Record Number 60311" a hyperlink. Any idea is greatly appreciated. Thanks,
  • May 26, 2011
  • Like
  • 0

Hey all,

 

I'm wondering if someone knows a workaround for a bug I encountered.

 

It seems that apex details inlineEdit function breaks when you add an actionFunction to the page.

 

In this example:

 

 

<apex:page standardController="bltn__c" extensions="bulletinController">

    <apex:form >
        <!-- The function that checks the users "awareness status" of the bulletin -->
        apex:actionFunction action="{!processAwareness}" reRender="none" name="jsProcessAwareness" />
        <apex:detail inlineEdit="true" relatedList="true" relatedListHover="true" showChatter="true" subject="{!$CurrentPage.parameters.id}"/>
    </apex:form>

    <script>
        window.onload = jsProcessAwareness();
    
    </script>

</apex:page>

 

public with sharing class bulletinController {
  
    public bulletinController(ApexPAges.StandardController controller) {
        
    }
    
    public void processAwareness() {
        usrBltn__c[] u = [SELECT id, awareness__c FROM usrBltn__c WHERE bulletin__c = :ApexPages.currentPage().getParameters().get('id') AND user__c = :userInfo.getUserId() AND awareness__c = 'Informed' LIMIT 1];
        if (!u.isEmpty()) {
            u[0].awareness__c = 'Viewed';
            update u;
        }
    }
}

 

I cannot inline edit the detail record.

I CAN when I remove the action function from the page.

 

I need a workaround please.

 

Thanks,

JNH

 

 

  • May 02, 2011
  • Like
  • 0

Hey all,

Does anyone know how to dynamically get listIds from Enhanced Lists?

 

ie: Bad practice:

 

 

<apex:enhancedList height="300" listId="00BM0000000LbS1" />

 

 

Good practice:

<apex:enhancedList height="300" listId="{!myListId}" />
  • April 26, 2011
  • Like
  • 0

All,

 

Where can I find a complete list of $Action global variable usage...

 

account.new, document.download....

 

I can't find it anywhere... (maybe I'm brain farting, or maybe they need better documentation.)

 

 

Also... if any moderators are reading: I can't actually search for "$Action" in the search engine - it ignores the $ - yes, even in quotes.

 

Thanks,

JNH

  • April 26, 2011
  • Like
  • 0

Hey all,

 

I'm working on building a component that allows a user to provision other users into following a record on chatter.

 

I have a wrapper class with an EntitySubscription obect in it, and a boolean for selection. I then use an apex:inputcheckBox on the vf compnent to enable selection by the user.

 

Problem is that it does not seem to be selecting...All I'm trying to do with the removeSelected() method below is add the index numbers to a list... It doesnt add anything, and the viewstate never shows any booleans as selected.

 

Please help.

 

 

CONTROLLER:

 

public with sharing class chatterUtils {

    //This is a specific entity Id to tie a user to via chatter
    public string parentId {get;set;}

    public string index {get;set;}

    public list<userRow> userRows {
        get {
            if (userRows == null) {
                userRows = new list<userRow>();
            }
            return userRows;
        }
        set;
    }

    public class userRow {
       public EntitySubscription rowEnt {get;set;}
       public boolean rowSelected {get;set;}
       public integer rowIndex {get;set;}
       public userRow(EntitySubscription rEnt, boolean rSel, integer rInd) {
           rowEnt = rEnt;
           rowSelected = rSel;
           rowIndex = rInd;
       }
    }

    public list<EntitySubscription> subs {get;set;}

    //Subscribe the list of users to the entity id
    public void provisionFollowers() {
        list<EntitySubscription> sub = new list<EntitySubscription>();
        for (userRow u : userRows) {
            entitysubscription e = u.rowEnt;
            sub.add(e);
        }
        insert sub;
    }

    public chatterUtils() {
        userRows.add(new userRow(new EntitySubscription(parentId = parentId), false, 0));
    }

    public void add() {
        userRows.add(new userRow(new EntitySubscription(parentId = parentId), false, userRows.size()));
    }

    //Remove the clicked row, and set the following indexs back by one
    public void remove(){
        userRows.remove(integer.valueOf(index));
        for (integer i = integer.valueOf(index); i < userRows.size(); i++){
            userRows[i].rowIndex -= 1;
        }
    }

    public list<integer> selectedIndexes = new list<integer>();
    public pageReference removeSelected(){
        for (integer i = 0; i<userRows.size(); i++){
            if (userRows[i].rowSelected) {
                selectedIndexes.add(i);
            }
        }
        return null;
    }
}

 

 

COMPONENT

 

<apex:component controller="chatterUtils" allowDML="true" >

    <apex:attribute assignTo="{!parentId}" description="The record Id that the user(s) will be provisioned to follow. This must be a chatter enabled object." name="parentId" required="true" type="string"/>

    <!-- jQuery-->
    <apex:includeScript value="{!URLFOR($Resource.BundledResources, 'jQuery/jquery-1.4.2.min.js')}"/>
    <apex:includeScript value="{!URLFOR($Resource.BundledResources, 'jQuery/jquery-ui-1.8.6.custom.min.js')}"/>

    <apex:form >
        <apex:actionFunction action="{!remove}" name="removeIndex" reRender="userRowTable" immediate="true">
            <apex:param assignTo="{!index}" name="index" value=""/>
        </apex:actionFunction>
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton action="{!add}" value="Add" reRender="userRowTable" immediate="true"/>
                <apex:commandButton action="{!removeSelected}" value="Remove Selected" reRender="userRowTable" immediate="true"/>
            </apex:pageBlockButtons>
            <apex:pageBlockTable value="{!userRows}" var="user" id="userRowTable">
                <apex:column headerValue="Action">
                    <apex:inputCheckbox value="{!user.rowSelected}"/>
                    <apex:commandLink value="Remove" immediate="true" onclick="removeIndex('{!user.rowIndex}')" reRender="none"/>
            </apex:column>
                <apex:column headerValue="User">
                    <apex:inputField value="{!user.rowEnt.subscriberId}" />
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>

</apex:component>

 

 

  • April 20, 2011
  • Like
  • 0

Does anyone know how to insert a FeedPost object with an "@mention" in it?

 

I've tried doing it manually, then querying for feedPost.body - and it just has plain text of "@UserName"

 

I assume I have to do something with an id or something in the string? Can't quite figure this out or find documentation.

 

 

Thanks,

JNH

  • April 13, 2011
  • Like
  • 0

All,

 

Seems like a pretty basic requirement... I'm trying to make a VF email template with the date/time of the context user...

 

If I cant use $user.TimeZoneSidKey in a formula to make some offsets... Then what else could I do? Write a big silly formula that takes into consideration daylight savings time just ot output the value that's already on the record?

 

:P

 

Thanks!

  • April 11, 2011
  • Like
  • 0

Hey guys,

 

I want to broadcast a message to all our SF users whenever they log into the org, something similar to Salesforce Maintenance pop up.

 

So the user logs into the org and the first thing he/she sees is a pop up screen. Basically, I want to display an IFRAME to all users whenever they log into the SF. After user see the popup then I will send the user to the main screen so he can continue his work.

 

I'm not sure whether there is a method or function that I can call in a SControl or a Visualforce page.

 

Any help is appreciated.

 

  • April 04, 2011
  • Like
  • 0

Hey all,

 

trying to figure out if there is anywhere out there where someone has made a single pageBlockTable/dataTable (whatever) that combines multiple objects, and uses pagination.

 

Use case would be something like:

a single list of History type happenings that tracks: new files, new notes, maybe a change in field value here and there - all in one quick list rather that multiples...

 

Paginaiton would be great if I could use "standardSet Controler" ( http://www.salesforce.com/us/developer/docs/pages/Content/pages_custom_list_controller.htm )

  • April 04, 2011
  • Like
  • 0

Hey all,

 

I've made this syncronous trigger:

 

 

trigger inventoryItemAfter on inventoryItem__c (after update) {

list<inventoryItem__c> itms = [Select
i.quantityOnHand__c,
i.lastSyncTime__c,
i.Id, (Select id, quantity__c, dateTime__c From iiQuantities__r)
From inventoryItem__c i
where i.Id IN :Trigger.newMap.keySet()
];

//Create a list of quantities
list<iiQuantity__c> qs = new list<iiQuantity__c>();

//For each inventory item that has been updated
for (inventoryItem__c i : Trigger.new) {
//If we have increased by one day
if (Trigger.oldMap.get(i.id).lastSyncTime__c.day() != i.lastSyncTime__c.day() ) {
//Then we insert a NEW history row item...
iiQuantity__c q = new iiQuantity__c(
inventoryItem__c = i.Id,
quantity__c = i.quantityOnHand__c
);
qs.add(q);
} else {
/*
//We just update the existing one...
iiQuantity__c q = i.iiQuantities__r[0];
q.quantity__c = i.quantityOnHand__c;
q.dateTime__c = dateTime.now();
qs.add(q);
*/
system.debug('\n\nTHESE ARE THE QUANTITIES: ' + i.iiQuantities__r + '\n\n');
}
}
//Do it now!!!
if (!qs.isEmpty()) {
upsert qs;
}
}

 But the iiQuantities__r is null!

 

I know it's not null, because when i run it in the eclipse org it returns 4 children... why is is empty in my debug log?

 

The relationship is master-detail

 

Debug:

 

16.0 APEX_CODE,DEBUG;APEX_PROFILING,INFO;CALLOUT,INFO;DB,INFO;VALIDATION,INFO;VISUALFORCE,INFO;WORKFLOW,INFO
13:01:30.158|EXECUTION_STARTED
13:01:30.158|CODE_UNIT_STARTED|[EXTERNAL]|01qM00000004Czg|inventoryItemAfter on inventoryItem trigger event AfterUpdate for [a0eM0000000J3W3]
13:01:30.159|SOQL_EXECUTE_BEGIN|[3]|Aggregations:1|Select
i.quantityOnHand__c,
i.lastSyncTime__c,
i.Id, (Select id, quantity__c, dateTime__c From iiQuantities__r)
From inventoryItem__c i
where i.Id IN :Trigger.newMap.keySet()

13:01:30.161|METHOD_ENTRY|[8]|MAP.keySet()
13:01:30.161|METHOD_EXIT|[8]|MAP.keySet()
13:01:30.171|SOQL_EXECUTE_END|[3]|Rows:1
13:01:30.171|METHOD_ENTRY|[17]|Datetime.day()
13:01:30.171|METHOD_ENTRY|[17]|MAP.get(ANY)
13:01:30.172|METHOD_EXIT|[17]|MAP.get(ANY)
13:01:30.172|METHOD_EXIT|[17]|Datetime.day()
13:01:30.172|METHOD_ENTRY|[17]|Datetime.day()
13:01:30.172|METHOD_EXIT|[17]|Datetime.day()
13:01:30.172|METHOD_ENTRY|[32]|System.debug(ANY)
13:01:30.172|USER_DEBUG|[32]|DEBUG|

THESE ARE THE QUANTITIES: ()


13:01:30.172|METHOD_EXIT|[32]|System.debug(ANY)
13:01:30.172|METHOD_ENTRY|[36]|LIST.isEmpty()
13:01:30.172|METHOD_EXIT|[36]|LIST.isEmpty()
13:01:30.972|CUMULATIVE_LIMIT_USAGE
13:01:30.972|LIMIT_USAGE_FOR_NS|(default)|
Number of SOQL queries: 1 out of 100
Number of query rows: 5 out of 50000
Number of SOSL queries: 0 out of 20
Number of DML statements: 0 out of 150
Number of DML rows: 0 out of 10000
Number of script statements: 4 out of 200000
Maximum heap size: 0 out of 3000000
Number of callouts: 0 out of 10
Number of Email Invocations: 0 out of 10
Number of fields describes: 0 out of 100
Number of record type describes: 0 out of 100
Number of child relationships describes: 0 out of 100
Number of picklist describes: 0 out of 100
Number of future calls: 0 out of 10

13:01:30.972|CUMULATIVE_LIMIT_USAGE_END

13:01:30.173|CODE_UNIT_FINISHED|inventoryItemAfter on inventoryItem trigger event AfterUpdate for [a0eM0000000J3W3]
13:01:30.173|EXECUTION_FINISHED

 

 

 

  • March 16, 2011
  • Like
  • 0

Hi,

 

I have an apex trigger on Case object that is supposed to automatically associate Cases to Contact records based on the AccountId field and its properties.

My trigger works well when I update existing Cases, but it throws the "attempt to de-reference a null object" error whenever I create a new Case.

 

This trigger first looks at the Email__c field set on the Account associated (Case.Account.Email__c) and tries to find existing contacts with that email address. If it didn't find a contact with that email address, it creates a Contact with some account info and associates it with the Case accordingly. If it did find contacts with that email address, it will query for them and associate them with the Case.

 

Here is my code (the line causing the error is highlighted in red):

 

trigger caseNSFBefore on Case (before insert, before update) {
    List<String> emailAddresses = new List<String>();
    List<String> accountIds = new List<String>();
    //First exclude any cases where the contact is set
    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null &&
            caseObj.AccountId != null)
        {
            accountIds.add(caseObj.AccountId);
            System.debug('AccountEmail*********' + accountIds);
            List<Account> listAccounts = [Select Id,Email__c, firstName__c, lastName__c, primePhone__c From Account Where Id in :accountIds];
            for (Account a :listAccounts){
            emailAddresses.add(a.Email__c);
            System.debug('AccountEmail*********' + emailAddresses);
            }

        }
    }
    //fetch all the Account records from database
    Map<Id, Account> mapAccounts = new Map<Id, Account>([Select Id, Email__c, firstName__c, lastName__c, primePhone__c From Account Where Id in :accountIds]);

    //Now we have a nice list of all the email addresses.  Let's query on it and see how many contacts already exist.
    List<Contact> listContacts = [Select Id,Email From Contact Where Email in :emailAddresses];
    Set<String> takenEmails = new Set<String>();
    for (Contact c:listContacts) {
        takenEmails.add(c.Email);
    }
    
    Map<String,Contact> emailToContactMap = new Map<String,Contact>();
    List<Case> casesToUpdate = new List<Case>();
    List<Case> casesToUpdate1 = new List<Case>();



    for (Case caseObj:Trigger.new) {
        if (caseObj.ContactId==null &&
            caseObj.AccountId !=null &&
           !takenEmails.contains(mapAccounts.get(caseObj.AccountId).Email__c))
        {
                List<Account> listAccounts = [Select Id,Email__c, firstName__c, lastName__c, primePhone__c From Account Where Id in :accountIds];
                for (Account a :listAccounts){
                    
                Contact cont = new Contact(FirstName= a.firstName__c,
                                            LastName= a.lastName__c,
                                            AccountId = a.Id,
                                            Phone = a.primePhone__c,
                                            Email= a.Email__c);
                emailToContactMap.put(mapAccounts.get(caseObj.AccountId).Email__c,cont);
                casesToUpdate.add(caseObj);
                
                }
        } else {
        casesToUpdate1.add(caseObj);    
        }
    }
    
    List<Contact> newContacts = emailToContactMap.values();
    insert newContacts;
    
    for (Case caseObj:casesToUpdate) {
        Contact newContact = emailToContactMap.get(mapAccounts.get(caseObj.AccountId).Email__c);
        
        caseObj.ContactId = newContact.Id;
    }
        for (Case caseObj:casesToUpdate1) {
        Contact existingContact = [select id from Contact where Email = :mapAccounts.get(caseObj.AccountId).Email__c  limit 1];        
        caseObj.ContactId = existingContact.Id;
    }
}

 

 

I would appreciate your help.

 

 

Thanks,

 

  • November 09, 2012
  • Like
  • 0

Hi all,

 

I have a scheduled report that needs to go out via email at 9:30 am every morning - not 9 or 10 (it's currently set to run at 10:00 am which is too late).

 

I understand the reporting limitations and I beleive reports can be scheduled to run every hour. More details can be found here: http://www.salesforce.com/us/developer/docs/packagingGuide/Content/dev_package_limits_for_pe_ge.htm.

 


What is the best practice when it comes to building such custom scheduled reports that can meet above requirement (AKA Runtime of every half  hour)?

 

Ideally, I would like such capability to be offered through the out-of-the-box features.

 

 

Kindly provide youre comments.

 

 

Regards,

 

  • October 22, 2012
  • Like
  • 0

All,

 

I have the Inline Editing enabled in my org and it works fine for my Opportunity object.

But I cannot beneft from this feature on some of the other standard objects such as Contacts, Accounts, and Cases.

 

I beleive this feature is available for all objects but for some reason I cannot seem to have it.

 

Please help.

 

Thanks,

 

 

  • August 29, 2012
  • Like
  • 0

Hey guys,

 

Contacts are a child of a Lead, so a Lead can have multiple contacts (Contacts >> Lead). Once the user converts the lead, I want to associate all of the child Contacts with the converted Account. I have a trigger as follows:

trigger leadAfter on Lead (after update) {

    //create a list of Contacts to update with Converted Account ID
    List< Contact > contacts = new list< Contact >();
   
  for ( Lead l : Trigger.new )
  {
    if (Trigger.old[0].isConverted == false && Trigger.new[0].isConverted == true) {
        System.debug('******Entering LeadAfter******');

        //Create a list of contacts that matches the Converted LeadId
        Contact c = [SELECT id, Lead__c, Name, AccountId FROM Contact c WHERE c.Lead__c = :l.Id AND c.AccountId = null];
       
        c.AccountId = l.ConvertedAccountId;
        contacts.add(c);
    }
        update contacts;
}
}

 

This trigger doesn't work and throws the following error: List has more than 1 row for assignment to SObject Trigger.leadAfter: line 12, column 21.

 

How can I update all of the child Contacts in a bulk manner?

 

Your input is appreciated.

 

  • July 22, 2011
  • Like
  • 0
Hi all, I have a controller that it's supposed to parse Subject line of an Email and extract a certain set of stings. For example, If the Subject line is [112233-notification number 22] - [Customer Support], I want to be able to extract only the "112233" portion of the text. I use the code below to find the index of "[" & index of last "-". String extract = c.Subject.substring(c.Subject.indexOf('[')+1, c.Subject.LastIndexOf('-')); However, I received "112233-notification number 22]" as my extract string. How should I go about locating only the "112233" part? My method needs to smart enough to locate only the integer between [ & - (within the closed [ ]). Appreciate your inputs.
  • June 06, 2011
  • Like
  • 0

Hi all,

 

I'm building an EmailMessage Trigger that is supposed to identify a case that was created by Email-To-Case feature and update a custom field called SuppliedToEmail__c with the ToAddress of the Email that has been invoked in this trigger.

 

My After Update is below:

trigger EmailMessageAfterUpdate on EmailMessage (After update) {
    for (EmailMessage newEmail : trigger.new){
    System.debug('******Entering EmailAfterUpdate******');

        if(Trigger.oldMap.get(newEmail.id).ParentId == null && newEmail.ParentId != null){
        Case c = [SELECT id, SuppliedToEmail__c FROM Case WHERE Id = :newEmail.ParentId];
            System.debug('******Entering EmailAfterUpdate\n'+c.CaseNumber+'******');
        c.SuppliedToEmail__c = newEmail.ToAddress;
        update c;
            System.debug('******Entering EmailAfterUpdate\n'+c.SuppliedToEmail__c+'******');
        }
    }
}

 

Unfortunately this trigger is not being invoked, I confirmed by ranning some tests and reviewing the debug logs.

 

I want to replicate the WebEmail (SuppliedEmail) field update, upon creation of a Email-to-Case record, to perform the same thing with my custom email field.

 

Your help is appreciated.

 

  • June 01, 2011
  • Like
  • 0

Hey all,

 

Our org uses a number of Email-to-Case processes, and we want to identify the ToAddresses used for the generated cases to leverage the workflow capacities. We are designing a IsInsert trigger that will automatically populate a custom field with the value of the ToAddress used.

 

The idea is very similar to the Web Email (SuppliedEmail) default page that associates a case with a originator's email address. In this trigger, we are doing a query for the originator's emailmessage and its information.

 

I'm not sure how to do the following:

1) Locate the email message that created the case. Would the code below locate the email that I'm loolking for?

         list<EmailMessage> email = [
         select
         id, ParentId, ToAddress
         from EmailMessage
         where ParentId = c.id  Limit 1];

2) Locate the ToAddress field. ToAddress in above query should be the Email-to-Case address for the created case c. Is that correct?

 

 

Thanks,

 

  • May 29, 2011
  • Like
  • 0
Hey guys, Can you provide a hyperlink or a link to a URL through a Error message displayed as part of a Trigger? For example, instead of hardcoding the URL as shown below, use a markup to make it a link: c.addError('ERROR TRM100: There is already an identical record: Record Number '+cs.Number+' (https://na8.salesforce.com/'+cs.Id+')'); This currently reads as: Error: Invalid Data. Review all error messages below to correct your data. ERROR TRM100: There is already an identical record: Record Number 60311 (https://na8.salesforce.com/500M0000000mJJ9IAM) It would be great if I could make the "Record Number 60311" a hyperlink. Any idea is greatly appreciated. Thanks,
  • May 26, 2011
  • Like
  • 0

Hey all,

 

I'm wondering if someone knows a workaround for a bug I encountered.

 

It seems that apex details inlineEdit function breaks when you add an actionFunction to the page.

 

In this example:

 

 

<apex:page standardController="bltn__c" extensions="bulletinController">

    <apex:form >
        <!-- The function that checks the users "awareness status" of the bulletin -->
        apex:actionFunction action="{!processAwareness}" reRender="none" name="jsProcessAwareness" />
        <apex:detail inlineEdit="true" relatedList="true" relatedListHover="true" showChatter="true" subject="{!$CurrentPage.parameters.id}"/>
    </apex:form>

    <script>
        window.onload = jsProcessAwareness();
    
    </script>

</apex:page>

 

public with sharing class bulletinController {
  
    public bulletinController(ApexPAges.StandardController controller) {
        
    }
    
    public void processAwareness() {
        usrBltn__c[] u = [SELECT id, awareness__c FROM usrBltn__c WHERE bulletin__c = :ApexPages.currentPage().getParameters().get('id') AND user__c = :userInfo.getUserId() AND awareness__c = 'Informed' LIMIT 1];
        if (!u.isEmpty()) {
            u[0].awareness__c = 'Viewed';
            update u;
        }
    }
}

 

I cannot inline edit the detail record.

I CAN when I remove the action function from the page.

 

I need a workaround please.

 

Thanks,

JNH

 

 

  • May 02, 2011
  • Like
  • 0

Hey all,

Does anyone know how to dynamically get listIds from Enhanced Lists?

 

ie: Bad practice:

 

 

<apex:enhancedList height="300" listId="00BM0000000LbS1" />

 

 

Good practice:

<apex:enhancedList height="300" listId="{!myListId}" />
  • April 26, 2011
  • Like
  • 0

Hey all,

 

I'm working on building a component that allows a user to provision other users into following a record on chatter.

 

I have a wrapper class with an EntitySubscription obect in it, and a boolean for selection. I then use an apex:inputcheckBox on the vf compnent to enable selection by the user.

 

Problem is that it does not seem to be selecting...All I'm trying to do with the removeSelected() method below is add the index numbers to a list... It doesnt add anything, and the viewstate never shows any booleans as selected.

 

Please help.

 

 

CONTROLLER:

 

public with sharing class chatterUtils {

    //This is a specific entity Id to tie a user to via chatter
    public string parentId {get;set;}

    public string index {get;set;}

    public list<userRow> userRows {
        get {
            if (userRows == null) {
                userRows = new list<userRow>();
            }
            return userRows;
        }
        set;
    }

    public class userRow {
       public EntitySubscription rowEnt {get;set;}
       public boolean rowSelected {get;set;}
       public integer rowIndex {get;set;}
       public userRow(EntitySubscription rEnt, boolean rSel, integer rInd) {
           rowEnt = rEnt;
           rowSelected = rSel;
           rowIndex = rInd;
       }
    }

    public list<EntitySubscription> subs {get;set;}

    //Subscribe the list of users to the entity id
    public void provisionFollowers() {
        list<EntitySubscription> sub = new list<EntitySubscription>();
        for (userRow u : userRows) {
            entitysubscription e = u.rowEnt;
            sub.add(e);
        }
        insert sub;
    }

    public chatterUtils() {
        userRows.add(new userRow(new EntitySubscription(parentId = parentId), false, 0));
    }

    public void add() {
        userRows.add(new userRow(new EntitySubscription(parentId = parentId), false, userRows.size()));
    }

    //Remove the clicked row, and set the following indexs back by one
    public void remove(){
        userRows.remove(integer.valueOf(index));
        for (integer i = integer.valueOf(index); i < userRows.size(); i++){
            userRows[i].rowIndex -= 1;
        }
    }

    public list<integer> selectedIndexes = new list<integer>();
    public pageReference removeSelected(){
        for (integer i = 0; i<userRows.size(); i++){
            if (userRows[i].rowSelected) {
                selectedIndexes.add(i);
            }
        }
        return null;
    }
}

 

 

COMPONENT

 

<apex:component controller="chatterUtils" allowDML="true" >

    <apex:attribute assignTo="{!parentId}" description="The record Id that the user(s) will be provisioned to follow. This must be a chatter enabled object." name="parentId" required="true" type="string"/>

    <!-- jQuery-->
    <apex:includeScript value="{!URLFOR($Resource.BundledResources, 'jQuery/jquery-1.4.2.min.js')}"/>
    <apex:includeScript value="{!URLFOR($Resource.BundledResources, 'jQuery/jquery-ui-1.8.6.custom.min.js')}"/>

    <apex:form >
        <apex:actionFunction action="{!remove}" name="removeIndex" reRender="userRowTable" immediate="true">
            <apex:param assignTo="{!index}" name="index" value=""/>
        </apex:actionFunction>
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton action="{!add}" value="Add" reRender="userRowTable" immediate="true"/>
                <apex:commandButton action="{!removeSelected}" value="Remove Selected" reRender="userRowTable" immediate="true"/>
            </apex:pageBlockButtons>
            <apex:pageBlockTable value="{!userRows}" var="user" id="userRowTable">
                <apex:column headerValue="Action">
                    <apex:inputCheckbox value="{!user.rowSelected}"/>
                    <apex:commandLink value="Remove" immediate="true" onclick="removeIndex('{!user.rowIndex}')" reRender="none"/>
            </apex:column>
                <apex:column headerValue="User">
                    <apex:inputField value="{!user.rowEnt.subscriberId}" />
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>

</apex:component>

 

 

  • April 20, 2011
  • Like
  • 0
Afternoon all,

Well, neophyte s-control writer here....attempting to write an s-control that will write to the account page, and start a workflow.  However, some accounts do not meet validation rules, and without error handling, it looks like the s-control goes through and completes but of course the workflow isn't triggered as the criteria is not met (the s-control doesn't update the account).  It is likely something small, but would anyone see the err in my ways???  (I am using a custom button that executes javascript...).

Code:
{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}

{
try {
var account = new sforce.SObject("Account"); 

account.id = '{!Account.Id}'; 
account.Four_Month_Blitz_One__c = 'TRUE';
account.Four_Month_Blitz_Two__c = 'TRUE';
result = sforce.connection.update([account]); 

window.parent.location.href="{!URLFOR($Action.Account.View, Account.Id,null , true )}";
}
{
catch(e)
alert("An error has occurred : " + e);
}
}

 Thanks all,

Nik  :smileytongue: