Search code examples
triggerssalesforceapex-codeapex

SalesForce - Sum records from another custom object


How Do I Sum records from another custom object?

Hi.

I created a new custom object, called "referrals".

Every record in this object has a couple of fields and also an "email" field.

In my "accounts" object, I created a new field - "number of referrals".

In this field, I want to get the total number of referrals that has the same email address as the account.

What's the best way to do that? I'm a Wordpress and PHP developer, no previous experience with SF.

Thanks!


Solution

  • The easiest way to do this is without code.

    If you make a Master Detail Field on Referral that looks up to the Account, you get what is called a MasterDetail relationship. This relationship allows fields on the Parent (in this case account) called rollup fields.

    After that on the account you can create a rollup field for the sum of child referrals and add criteria to filter by email.

    EDIT: Had to get my mind around this.

    The above works great except when filtering by email. Here is a work around for this.

    Create Referral Fields:

    • Email (Email) = for your email
    • Email Matches Parent (Formula, checkbox) = IF(Email__c == Account__c.Email__c, true, false)
    • Email Matches Parent Stamp (checkbox) = this is a value we will populate with workflow

    Create Account Fields:

    • Emails with My Email (rollup, on Referral) = Count of records where Email Matches Parent Stamp = true

    Create 2 workflow rules on referral:

    • created, and any time it’s edited to subsequently meet criteria, Email Matches Parent = true. Make a workflow action, Field update, that sets the Referral Email Matches Parent Stamp to true.
    • Do the same but a false, Field update to false

    Now you will be free to create your rollup as desired. On account, create a new field called Referrals with My Email, set to roll up on the Referral object, Count, and where Criteria, Email Matches Parent Stamp = true.

    This will give you a real time rollup based on that calculated field.

    Workflows: https://help.salesforce.com/apex/HTViewHelpDoc?id=creating_workflow_rules.htm

    Rollup Fields: https://help.salesforce.com/HTViewHelpDoc?id=fields_about_roll_up_summary_fields.htm&language=en_US