I have a roll up summary field on one of my objects. Because roll up summary fields do not support smart dates or formulas, I am forced to manually input a specific date range that I want to summarize child records from. Is it possible to update the roll up filter from apex? For example, if I scheduled apex to run at the start of each month, I want to change the roll up filter to only roll up records from the start of the current month. Is this possible?
No - or at least not unless you use something like apex-mdapi to talk to the Metadata API, which is possible, but which I would not consider the most expeditious solution to this objective.
I'd propose (at least) three options:
- Establish a custom checkbox field
This_Month__cthe child object. Write Scheduled Apex set to fire on the last day of the month (or the first of the next month) to query for all objects with
This_Month__cset and clear it. Use a Trigger or a Process Builder or Workflow Rule to set
truewhenever a new object is created whose date (if other than the created date) is in the current month. Then, build your Roll-up Summary Field using
This_Month__cas your filter rather than a date range.
- Use the same field and Process/Trigger as above, but instead of Scheduled Apex, do some malarky with scheduled actions. Add a new Date formula field on the child object
Last_Date_Valid__c, whose value is the last day of the month of that object's Date field (or Created Date, if you're using that). (Formula expression left as an exercise, but feel free to ask if you'd like help constructing it). Then, use a Process Builder or Workflow Rule Time-Dependent Action to unset
This_Month__czero days after
Last_Date_Valid__c. Again, build your Roll-up Summary Field using the
This_Month__cfield as your criterion.
- Install Declarative Lookup Rollup Summaries, build a rollup using the criteria you need (not a native Roll-up Summary Field) and run it in Scheduled mode, refreshing on the first of the month.
I'd recommend just going with DLRS because it will save you almost all of the implementation and maintenance.