• Alain Cabon
  • 11448 Points
  • Member since 2016

  • Chatter
  • 362
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
  • 2281
I have to delete alerts whne expiration datetime has reached today's datetime
My expiration datetime is showing as 2019-10-05T00:00:00.000Z
I want to delete this record on 5th Oct but I am getting unknown error parsing query when I execute in query editor:
Select Id from Alert_vod__c where Expiration_Date_vod__c <= system.now()

Please help.

  • September 28, 2019
  • Like
  • 0
I have a formula field that should be calculating the number of weekdays a case was open. If the case is closed it calculates weekdays between create and closed date; if case is open it calculates age from today and create date. However, I have a closed case that was opened Thursday 8/15/2019 and closed Monday 8/19/2019 and the number that is being returned is zero. Can anyone see my error?
If( IsClosed,

(CASE(MOD(Datevalue(CreatedDate) - DATE(1985,6,24),7),
0 , CASE(MOD(ClosedDate - CreatedDate ,7),1,2,2,3,3,4,4,5,5,5,6,5,1),
1 , CASE(MOD(ClosedDate - CreatedDate ,7),1,2,2,3,3,4,4,4,5,4,6,5,1),
2 , CASE(MOD(ClosedDate - CreatedDate ,7),1,2,2,3,3,3,4,3,5,4,6,5,1),
3 , CASE(MOD(ClosedDate - CreatedDate ,7),1,2,2,2,3,2,4,3,5,4,6,5,1),
4 , CASE(MOD(ClosedDate - CreatedDate ,7),1,1,2,1,3,2,4,3,5,4,6,5,1),
5 , CASE(MOD(ClosedDate - CreatedDate ,7),1,0,2,1,3,2,4,3,5,4,6,5,0),
6 , CASE(MOD(ClosedDate - CreatedDate ,7),1,1,2,2,3,3,4,4,5,5,6,5,0),
+ (FLOOR((ClosedDate - CreatedDate)/7)*5)
NOT(MOD( Datevalue(CreatedDate) - DATE (2000 ,1, 1) ,7)=0),
NOT(MOD( Datevalue(CreatedDate) - DATE (2000 ,1, 1) ,7)=1)), 1, 0)),

(CASE(MOD(Datevalue(CreatedDate) - DATE(1985,6,24),7),
0 , CASE(MOD(Today() - Datevalue(CreatedDate) ,7),1,2,2,3,3,4,4,5,5,5,6,5,1),
1 , CASE(MOD(Today() - Datevalue(CreatedDate) ,7),1,2,2,3,3,4,4,4,5,4,6,5,1),
2 , CASE(MOD(Today() - Datevalue(CreatedDate) ,7),1,2,2,3,3,3,4,3,5,4,6,5,1),
3 , CASE(MOD(Today() - Datevalue(CreatedDate) ,7),1,2,2,2,3,2,4,3,5,4,6,5,1),
4 , CASE(MOD(Today() - Datevalue(CreatedDate) ,7),1,1,2,1,3,2,4,3,5,4,6,5,1),
5 , CASE(MOD(Today() - Datevalue(CreatedDate) ,7),1,0,2,1,3,2,4,3,5,4,6,5,0),
6 , CASE(MOD(Today() - Datevalue(CreatedDate) ,7),1,1,2,2,3,3,4,4,5,5,6,5,0),
+ (FLOOR((Today() - Datevalue(CreatedDate))/7)*5)
NOT(MOD( Datevalue(CreatedDate) - DATE (2000 ,1, 1) ,7)=0),
NOT(MOD( Datevalue(CreatedDate) - DATE (2000 ,1, 1) ,7)=1)), 1, 0)))


I have built an automation tool to help with regression testing, and so far it works without any issues in the Summer 19' release. I had a sandbox reserved to test the automation tool in the Winter 2020 release, and I am unable to locate multi-select picklists and custom forums under related lists in the Winter 2020 preview of Salesforce.

I have used Selenium functions to locate elements, JavaScript, and JQuery, all which work on the Summer 19 release but not the Winter 2020 release.

User-added imageAAs you can see, I am able to locate the same value in the multi-select picklist with no issues..

User-added imageI am unable to locate the elements that I was able to locate in Summer 2019

Does anyone have any idea why this may be happening?

I have below error, what can be reason:

Non static method cannot be referenced from a static context: void ContractTriggerHandler.OnAfterUpdate(List<Contract>, List<Contract>, Map<Id,Contract>, Map<Id,Contract>)

Any suggestions ?
I'm trying to figure out how to add X amount of days to a date through the lightning component controller. Here is what I have been trying:

.cmp - 
<aura:component implements="flexipage:availableForAllPageTypes">
        <aura:attribute name="dataInValue" type="Date" />
        <aura:attribute name="dataEndValue" type="Date"/>

        <lightning:input aura:id="startDate" type="date" label="Enter Date" value="{!v.dataInValue}" onchange="{!c.validDate}"/>
        <lightning:input aura:id="endDate" type="date" label="Day they get benefits:" value="{!v.dataEndValue}"/>
.js - 
    validDate : function(component,event,helper){
               var data_in = component.get("v.dataInValue");
               var data_out = formatDate(data_in) + 30;
               component.set("v.dataEndValue", data_out);
I aa trying to use process builder to create an event at 9:15 on the same date as another event. my formula is

DATETIMEVALUE(TEXT(YEAR([Event].StartDateTime ))+"-"+TEXT(MONTH([Event].StartDateTime ))+"-"+TEXT(DAY([Event].StartDateTime ))+" 09:15:00")

but I get a syntax error.

Can anyone assist with debugging please?

I wrote a lightning/aura component. This component lists all the orders associated with a case. When I running a SOQL query, I am getting 5 unique orders for a particular case, for example. But when I am looking at the lightning component, its displaying the same order 5 times. So I am thinking that the aura component is not iterating the apex list properly. I have the code below. Can anyone pinpoint, where I might have gone wrong?

Apex controller:
public class CC_OrderListController {
    public static List <Order> getOrders(Id caseId) {
        Case c = [select ContactId from Case where Id = :caseId LIMIT 1];
        Id con = c.ContactId;
        List<Order> result = [SELECT Id, BillToContact.Email, EffectiveDate, Sub_Total__c, External_Order_URL__c FROM Order where BillToContactId = :con ORDER BY createdDate DESC LIMIT 20];
        return (result == null ? new List<Order>() : result);

Aura component:
<aura:component implements="flexipage:availableForAllPageTypes,force:hasRecordId" controller="CC_OrderListController" access="global">
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>

    <aura:handler name="init" value="{! this }" action="{! c.init }"/>

    <div style="min-height: 200px;">
                data="{! v.data }"
                columns="{! v.columns }"

Aura JS controller:
    init : function(component, event, helper) {
        component.set('v.columns', [
            {label: 'Email', fieldName: 'Email', type: 'text'},
            {label: 'Order Date', fieldName: 'EffectiveDate', type: 'Date'},
            {label: 'Sub Total', fieldName: 'Sub_Total__c', type: 'currency'},
            {label: 'Order Link', fieldName: 'orderLink', type: 'url'}

        var fetchData = {
            Email: "",
            EffectiveDate : "",
            Sub_Total__c : "",
            orderLink: ""


JS Helper method:
    fetchData : function(component, fetchData) {
        var action = component.get('c.getOrders');
        action.setParams({ "caseId" : component.get('v.recordId') });
        var self = this;
        var results = [];
        action.setCallback(this, function(actionResult) {
            var res = actionResult.getReturnValue();
            for(var i = 0; i < res.length;i++){
                fetchData.Email = res[i].BillToContact.Email;
                fetchData.EffectiveDate = res[i].EffectiveDate;
                fetchData.Sub_Total__c = res[i].Sub_Total__c;
                fetchData.orderLink = res[i].External_Order_URL__c;
            component.set('v.data', results)

Should I use aura iteration tag ? Any help would be greatly appreciated. Thank you
Hi dev team,

I have created a custom object with questions and corresponding marks detailed in several text and number fields to be displayed in a specific graph. The request is to create a Spider Chart.
Is there a existing Ligtning component for this sort of chart?
Or do you advise anything else?

Thank you.
Best Regards,
Hello friends, 

Please help me with a simple query to get records if data A is > date B. I tried this soql query in query builder but it give error. 

Select Forecast_Handover__c,Name,Site__c,Forecast_Sales_Date__c from Cbd_plot__c where  Forecast_Handover__c > Forecast_Sales_Date__c

both these forecast date fields are date fields in salesforce I am getting error 'Unknown error parsing query'

but at the same time is I try 

Select Forecast_Handover__c,Name,Site__c,Forecast_Sales_Date__c from Cbd_plot__c where  Forecast_Handover__c > TODAY

its returning me records. 

Many thanks in advance
my challenge when doing the above mentioned module fails with the following error:

"The test method doesn’t insert an opportunity with the correct fields. Double check the Name, StageName, and CloseDate and try again."

The requirement is as follows:
In the test method, create an opportunity with the following fields.
Name: 'Sell 100 Widgets'
StageName: 'Prospecting'
CloseDate: Date.today().addMonths(3)

And the code is this:
    Opportunity opp =  new Opportunity(Name='Sell 100 Widgets',
    insert opp;

Any idea what could be wrong?

Hi all,
I have just started in a new company with an old very customize Salesforce instance. I have just discovered that an object has 25.000 new records created each week.
My question is how can I find which process / workflow / trigger or Apex is created these records? 
Thank you for your help.
I am working on validation for IPV4 and IPV6 to validate their input.
This IP input fields should also accept the subnet mask.

Valid input in IPV4 field can be :

Valid input in IPV6 field can be :

Is it something possible with regex or custom code? I tried couple of regex solutions but its not working. 
I am new to Sales force API integration with .NET and came accross this issue - can't seem to get the sObject id from QueryResult - the id is null, even though a valid record is returned, and I can see the Name field. Any suggestions?
See my query below:

  string queryStr = $"SELECT id, Name FROM Account Where Name = '{name}'";
                QueryResult qResult = _service.query(queryStr);
                bool done = false;

                if (qResult.size > 0)
                        sObject[] records = qResult.records;

                        for(int i = 0; i < records.Length; i ++)
                            accountId = records[i].id; // record id is null here

                        if (qResult.done)
                            done = true;
                            qResult =
I have a method called getAccountIds, that is successfully returning a set of Account Ids. I second method that is countContacts(List<Id>acctIds). But when I return the acctIds, it doesn't get added picked up by the second method.
I'm calling the class from an execute anonymous window like this --> 

Actual Class and methods. 
public class AccountProcessor {
    public static List<Id> getAccountIds(){
        List<Id> acctIds = new List<Id>(); 
        For(Account a:[SELECT Id FROM Account LIMIT 200] ){
        System.debug('The list of Ids = ' + acctIds); 
        System.debug('The size of List = ' +acctIds.size());
        return acctIds; 
    public static void  countContacts(List<Id> acctIds){
       	//Declare Variables.
       	Account accountToUpdate; 
        List<Account> accountsToUpdate = new List<Account>(); 
       	Integer totalContacts = 0; 
        System.debug('Size of List =' + acctIds.size());
        List<Contact> cons = [SELECT Id, AccountId FROM Contact WHERE AccountId IN: acctIds]; 
        System.Debug('Contact List = ' + cons.size()); 
        //Loop through the contacts and sum the account Id for each contact. 
        for( Id a : acctIds){
            System.Debug('Account Ids on Contact = ' + a); 
          	Contact[] contactIdArray = new List<Contact>();  
                   for(Contact c : cons){
                      // System.debug('Enter Contact Loop ');
                      // System.Debug('Account Id = ' + a);
                       Boolean resultType = a.equals(c.AccountId);
                       //System.Debug('ResultType is ? ' + resultType); 
             accountToUpdate = [SELECT Id FROM Account WHERE Id =: a LIMIT 1]; 
             totalContacts = contactIdArray.size();
             accountToUpdate.Number_of_Contacts__c = totalContacts; 
             System.debug('Total Contacts = ' + totalContacts);
             System.debug('Total Update Accounts = ' + accountsToUpdate.size());
       update accountsToUpdate; 


We want to share a scratch org between two developers. How could we do?

Trying to replicate this https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_flows_lightningruntime.htm
 but getting error here is my code. 

<aura:application access="global"  extends="ltng:outApp" implements="ltng:allowGuestAccess">
	<aura:dependency resource="lightning:flow"/>
VF Page: 
<apex:page >
         <apex:includeLightning />
      <body class="slds-scope">
         <div id="flowContainer"/>
            var statusChange = function (event) {
               if(event.getParam("status") === "FINISHED") {
                  // Control what happens when the interview finishes
                  var outputVariables = event.getParam("outputVariables");
                  var key;
                  for(key in outputVariables) {
                     if(outputVariables[key].name === "myOutput") {
                        // Do something with an output variable
            $Lightning.use("c:FlowVFPage", function() {
               // Create the flow component and set the onstatuschange attribute
               $Lightning.createComponent("lightning:flow", {"onstatuschange":statusChange},
                  function (component) {
                     // Set the input variables
                     // Start an interview in the flowContainer div, and 
                     // initializes the input variables.
                     component.startFlow("New_Customer", inputVariables);

How to solve this error? thanks in Advance. 

Hi everyone. I work with small project and ran into a problem. I need to display the most popular genre of the song in the mix object and the second after it, how can I do it using the main syntax of SOQL. If you give SOQL code or example it would be cool.
User-added image
Hi everyone

I build a custom lightning web component (lwc) with a datatable and a wire-function with an apex-controller.
If i place the lwc on the lightnig record page an error appears:

Looks like there's a problem.

Unfortunately, there was a problem. Please try again. If the problem continues, get in touch with your administrator with the error ID shown here and any other related details. An internal server error has occurred Error ID: 747686150-78663 (1184503911)

Here is a screenshot with the error: https://i.imgur.com/3Ov7PnQ.png

No error in debug log and no error is shown up in browser-console.
I have no reason why this happen. Has anyone some suggestions?

    <div class={flexipageRegionWidth}>
        <div class="slds-m-top_medium slds-m-bottom_x-large">

            <!-- Simple -->
            <template if:true={data}>
                <div class="slds-p-around_medium lgc-bg">
        <!-- Data failed to load -->
        <template if:false={data}>
            <div class="slds-text-color_error">
                An error occurred while loading.

import { LightningElement, wire, track, api } from 'lwc';

import { getObjectInfo } from 'lightning/uiObjectInfoApi'; // https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.reference_wire_adapters_object_info
import RSSFEED_OBJECT from '@salesforce/schema/RSSFeed__c';

import getFilteredRssFeeds from '@salesforce/apex/RssFeedController.getFilteredRssFeeds';

export default class RssFeed extends LightningElement {
    @api flexipageRegionWidth; // https://developer.salesforce.com/docs/component-library/documentation/lwc/use_width_aware
    @api recordId;// Public property. Id of brand-record.
    @api columnNames = undefined; // Public property. Set by lightning app builder.
    objectInfo = undefined; // 

    hideCheckboxColumn = true; // If true, the checkbox column for row selection is hidden.

    @track data;
    @track error;

    @track columns;
    @track tableLoadingState = true;

    @wire(getObjectInfo, { objectApiName: RSSFEED_OBJECT })
    wireObjectInfo({error, data}){
        console.log('>>>wireObjectInfo called.');

        if (data) {
            console.log('>>>data: ' + JSON.stringify(data, null, '\t'));
            this.objectInfo = data;
            this.error = undefined;

        } else if (error) {
            console.error('>>>error: ' + JSON.stringify(error, null, '\t'));

            this.error = error;
            this.objectInfo = undefined;
    @wire(getFilteredRssFeeds, { brandId: '$recordId' })
    wiredFilteredRssFeeds({error, data}){
        console.log('>>>wiredFilteredRssFeeds called.');

        if (data) {
            console.log('>>>' + JSON.stringify(data, null, '\t'));
            this.data = data;
            this.error = undefined;
        } else if (error) {
            console.error('>>>' + JSON.stringify(error, null, '\t'));
            this.error = error;
            this.data = undefined;

        console.log('>>>_prepareTableColumns called.');
        this.columns.forEach(column => {
            let columnLabel = ((this.objectInfo) ? this.objectInfo.fields[column.fieldName].label : '');
            column.label = columnLabel;
            console.log('>>>column' + JSON.stringify(column, null, '\t'));

    * https://developer.salesforce.com/docs/component-library/documentation/lwc/create_lifecycle_hooks_dom.html
    * The connectedCallback() lifecycle hook fires when a component is inserted into the DOM.
    async connectedCallback() {
        console.log('>>>async connectedCallback called.');
        this.tableLoadingState = false;
        console.log('>>>this.columnNames: ' + this.columnNames);

        this.columns = JSON.parse(this.columnNames);
        console.log('>>>this.columns: ' + JSON.stringify(this.columns, null, '\t'));

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="RssFeed">
        <targetConfig targets="lightning__RecordPage">
            <property default="[{ 'label': 'Title', 'fieldName': 'Title__c' },{ 'label': 'Description', 'fieldName': 'Description__c' },{ 'label': 'Link', 'fieldName': 'Link__c', 'type': 'url', 'fixedWidth': 200 },{ 'label': 'Date', 'fieldName': 'Date__c', 'type': 'date', 'fixedWidth': 100 }]" description="Specifies which columns are displayed." label="Column Names" name="columnNames" required="true" type="String"/>

Here is the apex-controller:
* Is used for lightning web component (lwc) named rssFeed.
* Query relevant rss feed filtered by Id of Brand (Brand__c).
* @author: <Christian Schwabe> (Christian.Schwabe@colliers.com)
* @history:
* version		    | author				                                | changes
* ====================================================================================
* 0.1 08.05.2019	| Christian Schwabe (Christian.Schwabe@colliers.com)	| initial version.
public with sharing class RssFeedController {

    * Query RSS-Feed records filtered by Id for Brand (Brand__c).
    * @param  brandId          Id for Brand (Brand__c)
    * @return List<Brand__>
    public static List<RSSFeed__c> getFilteredRssFeeds(Id brandId){
        List<RSSFeed__c> listOfRssFeed = new List<RSSFeed__c>();
        for(RSSFeed__c rssFeed : [SELECT Id, Link__c, Title__c, Author__c, Description__c, Date__c FROM RSSFeed__c WHERE Brand__c = :brandId]){
            rssFeed.Description__c = String.valueOf(rssFeed.Description__c).stripHtmlTags();


        return listOfRssFeed;

So I have object Account.name which I need to take the last word of the string and place it at the beginning. For example, I have John and Jamie Jones and I need the custom field to read: Jones, John and Jamie

I'm trying to accomplish OpportunityChangeTrigger challenger from trailhead but I found one error and I don't know how to address it.
The error is:
The trigger doesn't create the expected task for opportunities whose stage has been updated to 'Closed Won'.

This is my code for the trigger:
trigger OpportunityChangeTrigger on OpportunityChangeEvent (after insert) {
    List<Opportunity> opps = new List<Opportunity>();
    List<Task> taskList = new List<Task>();
    for(OpportunityChangeEvent event : Trigger.New){
        EventBus.ChangeEventHeader header = event.ChangeEventHeader;
        if(header.changeType == 'UPDATE' && event.isWon){
			Task task = new Task();
            task.subject = 'Follow up on won opportunities: ' +header.recordIds;
        insert taskList;


And this is the  test class
public class TestOpportunityChangeTrigger {
    @isTest static void testCreateAndUpdateEmployee(){
        insert new Opportunity(Name='Sell 100 Widgets', StageName='Prospecting', CloseDate=Date.today().addMonths(3));
        Opportunity[] oppList = [SELECT Id,StageName FROM Opportunity];
        for (Opportunity opp : oppList){
          opp.StageName = 'Closed Won';
          update opp;
        Task[] taskList = [SELECT Id FROM Task];
        System.assertEquals(1, taskList.size(),'The change event trigger did not create the expected task.');

We're creating a new report file structure and are trying to find a way to move multiple reports into a folder at once. Is there a way to do a mass upload (like something using data loader) or is this something that will need to be done one by one?
Hey guys, 

i have read several articels about best practice for triggers. Most of the 'rules' are easaly to understand and logical. 

One of the rules is 'less logic trigger'. I understand that it doesn't make sense to write very complex triggers.  But in my opinion, when i have one trigger per object, at least i have to tell trigger when he needs to fire the specific classes. 

To be more specific: 

I have three classes, each of them should be fired after a specific update: 

- 1 classe creates a copy of the opportunity (fire after closed won)
- 1 class creates different tasks (fire after the owner has changed)
- 1 class for an apex callout (fire after field is updated for the first time) 
- 1 class for handle recursion

All of these classes are related to the opportunity object. So i have to create one trigger with the context variable (after update).  Sometimes i can handle the logic within the class but often i need the trigger.oldmap variable to make sure, that the trigger act like it should.

so my trigger would look sth like
trigger opptrigger on Opportunity (after update) {

for (Opportunity opp : trigger.new){


Opporuntiy oldOpp = trigger.oldMap.get(opp.Id)

if( !oldOpp.isWon && opp.isWon){
// class for copy creation

if( !oldOpp.OwnerId != opp.OwnerId){
// class for owner change

&& !String.IsEmpty(old.Field__c)){
// class for callout

I need Help on Test class with assert how to add assert in this test class

public class TestClass{
    public static Account returnAccount(Id ParentId) {
        return [Select Name, FirstName, LastName, Id from Account where id =: ParentId];
    public static void test(){
    Account a = new Account();
    insert a;
    //need add assert here if I comment above line assert has to fail o/w it hass to pass

I need to be able to connect each Email Alert with any associated Workflow Rules.  I've been able to pull all the data using the Tooling API and querying the WorkflowRule and WorkflowAlert objects.  The Email Alert is associated to the Email Template in these exports,however, that does not export a field that connects Workflow Rules and Email Alerts? Is there a way to do this? I have 200+ I am looking at and really don't want to do it by hand.

I've also looked at Workbench, but it does not have a connecting field either.
I have a lightning component embedded in a flow, how do I pass the recordId from the flow into the lightning component?

Everything I have found shows the old flow designer.  The new lightning flow designer does not have an option to set input fields on the lightning component.

I want to query permissions data for various objects in our SF instance. I'm able to query PermissionsRead and PermissionsEdit from FieldPermissions, but I also want to pull data broken down similar to the screenshot below, but for fields in the object.
User-added image

I'd also like to be able to query what fields are shown in each page layout and which profile is assigned each page layout for the object.

Is this possible?
I am tring to create a formula that will provide the same output as Excel's Rate function. Havent been abe to find anything online or in the forum. Any help is greatly appreciated!

Example from Excel:  =RATE(120,-468.67,27483,,0)*12
This formula produces a value of 16.48%
Term Months120
Monthly Loan Payment468.67
Financed Amount27,483.00
We are looking to add a field to the Opportunity called Contract Terms. We want this field to look at all products associated with the opportunity and find the earlieast start date and the latest end date?

Any ideas?
Hello, I am trying to iterate over a list of SObjects, but I'm not sure how to get it to display.

Here is the controller
public with sharing class RandomRecordAudit {
    public static map<string, string> getAllObjects(){
        map<string, string> objectList = new map<string, string>();
        for ( Schema.SObjectType o : Schema.getGlobalDescribe().values() )
            Schema.DescribeSObjectResult objResult = o.getDescribe();
            objectList.put(objResult.getName(), objResult.getLabel());
        return objectList;

Here is the JS file
import { LightningElement, track } from 'lwc';
import getAllObjects from '@salesforce/apex/RandomRecordAudit.getAllObjects';
export default class SObjectList extends LightningElement {
        @track objects;
        @track error;
        handleLoad() {
                .then(result => {
                    this.objects = result;
                .catch(error => {
                    this.error = error;

and here is the HTML
    <lightning-card title="ApexImperativeMethod" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <template if:true={objects}>
                <template for:each={objects} for:item="object">
                    <p key={object.Id}>{object.Name}</p>
            <template if:true={error}>
                <c-error-panel errors={error}></c-error-panel>

Any help is greatly appreciated, thanks!​​​​​​​
Hi all, I'm trying to create a flow that looks at Object A, evaluates three fields, and creates a new record on Object B. A new record on Object B should only be created if there isn't already an Object B record with identical data in those three fields.

For example, Object A record has cat, dog, bird filled into the three fields, respectively. Create an Object B record if there isn't already an Objet B record with cat, dog, bird filled into the same three fields.

Is this possible? 
share records with the end user when created by batch class
I have a requirement:

For an account in user's territory, we have calls created. Now based on this I need to create alerts where user can view alerts showing his account got calls on which date by which user in last 7 days. For this I need to create a batch but since all alerts are created by admin end user do not have access to alerts. How to fix this?
Please find my code below:

global class BatchCreateAlertforCalls implements Database.Batchable<sObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {  
    String query = 'SELECT Id,Call_Date_vod__c,Account_vod__c,createdby.name FROM Call2_vod__c where Status_vod__c = \'Submitted_vod\' AND Call_Date_vod__c = N_DAYS_AGO:7 AND OwnerId!=\'005U0000001vQ0a\'';
        return Database.getQueryLocator(query);
    global void execute(Database.BatchableContext BC, List<sObject>scope) {
        List<Call2_vod__c> callList = (List<Call2_vod__c>) scope;
        system.debug('call list>>>>'+calllist);
        List<Alert_vod__c> alertsubmittedcalllist = new List<Alert_vod__c>();
        for(Call2_vod__c call: callList){
         Alert_vod__c alert = new Alert_vod__c();
            alert.Activation_Date_vod__c = system.now();
            alert.Alert_Text_vod__c = call.Account_vod__c+' seen by '+call.createdby.name;
            alert.Link_Reference_vod__c =call.Id;
            alert.Expiration_Date_vod__c = system.now()+1;
        if(alertsubmittedcalllist.size() >0)
            insert alertsubmittedcalllist;
            system.debug('alert list>>>>'+alertsubmittedcalllist);
     global void finish(Database.BatchableContext BC) {
        // execute any post-processing operations
  • September 27, 2019
  • Like
  • 0
Hi guys,
We just created a library named R.apex, which helps simplify the common tasks in apex code development by adopting a functional style.
It offers tons of utility functions to work with lists, sets, maps and sobjects, making apex code clean and readable. We were suffering from the pain points of writing similar Apex code to complete trivial tasks once and once again, and that is the reason why we want to stop that and start to write reusable code. Here are some examples of what R.apex can do:
// Reverse a list
List<Integer> reversedList = R.of(new List<Integer>{ 1, 2, 3 })
// Fina specific account
List<Account> accountList = ...;
Account acc = (Account)R.of(accountList)
    .find(R.whereEq.apply(new Map<String, Object>{
        'LastName' => 'Wilson',
        'IsDeleted' => false

Hopefully R.apex can help make your Apex code development easier, and you are always welcome to give feedback so that we can improve it.

R.apex is an open source project hosted at https://github.com/Click-to-Cloud/R.apex/.
You can check it out. Feel free to clone it, make changes or submit a PR.


When someone takes the time/effort to repspond to your question, you should take the time/effort to either mark the question as "Solved", or post a Follow-Up with addtional information.  


That way people with a similar question can find the Solution without having to re-post the same question again and again. And the people who reply to your post know that the issue has been resolved and they can stop working on it.