• JSingh9
  • NEWBIE
  • 79 Points
  • Member since 2016
  • Salesforce Developer

  • Chatter
    Feed
  • 2
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 1
    Questions
  • 24
    Replies

I need to calculate the out of office hours in apex.

The hours are:
6 pm – 9 am Mon – Fri
and
6 pm on Fri till 9 am on Mon

I've already configured the Business Hours:

Monday09:00to18:00
Tuesday09:00to18:00
Wednesday09:00to18:00
Thursday09:00to18:00
Friday09:00to18:00
Saturday24 Hours
Sunday24 Hours

and activate it in Salesforce.

Please advise how it can be achieved in apex?

Hi all,

I am quite new to triggers. Using the forum I was able to create a trigger to prevent delete based on a picklist value. Now I am trying to write a trigger that will prevent delete based on 'who' the record is Createdby. We do not want users to be able to delete records created by the site user. Unfortunately I am not able to figure this one out. Can anyone help with the code?

Thanks!

trigger  DeleteJobApplication   on  cxsrec__cxsJob_application__c(before delete){
if(system.Trigger.isDelete){
String Userid=[SELECT id,Name FROM User WHERE Id =:UserInfo.getuserid()].Name ;
    for(cxsrec__cxsJob_application__c  J:Trigger.old){
          if(J.Createdby == 'ResourceManager Profile' ){
             J.addError('Je kan de inschrijving niet verwijderen wanneer deze is gemaakt door de site user');
            }
     }
     }
     }

Any one can help on this?

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: KJQNZRHU

Alhtough I used a new org

trailhead Challenge https://trailhead.salesforce.com/trails/automate_business_processes/modules/workflow_migration/units/workflow_migration_criteria
I want to retrieve all contacts with paging support. Such that my organizaion has 7000 contacts, I need to read 100 contcats per api call with paging support. How to accomplish this using SSQL through REST API?

I'm using this api:
https://ap5.salesforce.com/services/data/v42.0/query?q=SELECT Id,FirstName,LastName FROM Contact

Same paging support need for all the modules: leads, accounts, notes, events and tasks etc.

Thanks,
Guna.

Hello,

I am figuring out ways to replace our javascript buttons to lightning compatible one. We have quite a lot of javascript button one of which is "Send with Docusign" that lets a user send a contract using Docusign. I'm calling the right docusign template using this custom button & passes some parameters like recipient email. I have a part of code that validates if the contract is approved by the leads before it could be sent to client with docusign. Something like this:

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")}; 
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")} 

var contrObj = new sforce.SObject("Contract"); 
contrObj.id = "{!Contract.Id}"; 
var ContrStatus="{!Contract.Contract_Status__c}"; 
var profile ="{!User.Profile}"; 

if(ContrStatus!='Approved') 

alert("The contract should be approved before sending for signature"); 

else{ 
window.location.href = '/apex/dsfs__DocuSign_CreateEnvelope?DSEID=0&SourceID={!Contract.Id}&CRL=Email~{!Contract.Business_Contact_Email_Formula__c};FirstName~{!Contract.Business_Contact_First_Name__c};LastName~{!Contract.Business_Contact_Last_Name__c},.....................'; 
}

Now, I need to replace this javascript button with components that are lightning compatible (since we are plannign to switch to Lightning) . I'd like to know what are the possible options?

Thank you very much in advance!

Hi Guyz,

I've written a batch class for updating records and its working for 10000 records. I've to update more than 1 lacs records using API call and as I know the JSON limit is 10000. So can anyone help me out for solving this issue? How to pass multiple calls one by one? Please check my code and suggest me for solution. Thanks in advance.
**********
global class AccountDataSyncBatch implements Database.Batchable<sObject>, Database.AllowsCallouts, Schedulable, Database.stateful{
 
   global String lastAccountId;
   global String lastContactId;
   global String lastOpportunityId; 
   global boolean isStart;
   
   global AccountDataSyncBatch(){
      /* lastAccountId = accId;
       lastContactId = conId;
       lastOpportunityId = oppId;
       isStart = tempStart; */
   }
   
   global Database.QueryLocator start(Database.BatchableContext BC){
      //return Database.getQueryLocator('SELECT Id FROM User LIMIT 1');
      string query = 'SELECT Id, name, Account_Lead_Score__c,Relative_Performance__c, (select id, name,Contact_Lead_Score__c from contacts), (select id, name, Opportunity_Lead_Score__c from opportunities) from account';
      return Database.getQueryLocator(query);
   }

    
   global void execute(Database.BatchableContext BC, List<sObject> scope){
        fetchData();
   }    
    
    global void fetchData(){
        
          //navikAuthDomain.response mapResp = navikAuthentication.getMapId(UserInfo.getUserEmail());
            Http http = new Http();
            HttpRequest request = new HttpRequest();
         // request.setHeader('sessionToken',mapResp.sessionToken);
            request.setHeader('sessionToken', 'UNUEXHA0//SLWpBR9J3v6gEN5hHsbQd0C79nFkpelRojiBfhF6Yth2dZi6oawXSRYDE6AFRGsN0gpV3N0XMrqAkynQ5ZWSmcGT3QAomh3f0=');
            if(isStart = true){
                request.setEndpoint(Label.AccountContactOpportunity_Dump_API); 
            }
            
            request.setMethod('GET');
            HttpResponse response = http.send(request);
            
            if (response.getStatusCode() == 200) {
                DataSyncBatchHelper.ParentData parentData = (DataSyncBatchHelper.ParentData)JSON.deserialize(response.getBody(), DataSyncBatchHelper.ParentData.class);
                system.debug(parentData);
                
                if(parentData != null && parentData.data != null){
                    List<Account> accList = new List<Account>();
                    List<Contact> conList = new List<Contact>();
                    List<Opportunity> oppList = new List<Opportunity>();
                    
                    //****************Accounts***********
                    if(parentData.data.accounts != null && parentData.data.accounts.size() > 0){
                        for(DataSyncBatchHelper.Accounts account : parentData.data.accounts){
                            if(account.accountNumber != null && account.accountNumber.startsWith('001')){
                                accList.add(new Account(Id = account.accountNumber,
                                                                 Account_Lead_Score__c = account.accountleadScore,
                                                                 Relative_Performance__c = account.relative_Performance));
                            system.debug(accList);
                            }
                        }
                        if(accList.size() > 0){
                        Database.update(accList, false);
                        }
                      //****************Contacts************
                      if(parentData.data.contacts != null && parentData.data.contacts.size() > 0){
                        for(DataSyncBatchHelper.Contacts contact : parentData.data.contacts){
                            if(contact.contactId != null && contact.contactId.startsWith('003')){
                                conList.add(new Contact(Id = contact.contactId,
                                                                 Contact_Lead_Score__c = Decimal.valueOf(contact.contactLeadScore)));
                            system.debug(conList);
                            }
                        }   
                          if(conList.size() > 0){
                        Database.update(conList, false);
                        }
                        
                       //*****************Opportunity***************
                       if(parentData.data.opportunities != null && parentData.data.opportunities.size() > 0){
                        for(DataSyncBatchHelper.Opportunities opportunity : parentData.data.opportunities){
                            if(opportunity.opportunityId != null && opportunity.opportunityId.startsWith('006')){
                                oppList.add(new Opportunity(Id = opportunity.opportunityId,
                                                                          Opportunity_Lead_Score__c = Decimal.valueOf(opportunity.Opportunity_Score)));
                            system.debug(oppList);
                            }
                        } 
                         if(oppList.size() > 0){
                        Database.update(oppList, false);
                        }  
                      
                
                       }}}}}}
    
             
   global void finish(Database.BatchableContext BC){
        
           }
    
    global void execute(SchedulableContext sc){
      database.executebatch(new AccountDataSyncBatch());
   } 

}
 
  • July 18, 2017
  • Like
  • 0

I need to calculate the out of office hours in apex.

The hours are:
6 pm – 9 am Mon – Fri
and
6 pm on Fri till 9 am on Mon

I've already configured the Business Hours:

Monday09:00to18:00
Tuesday09:00to18:00
Wednesday09:00to18:00
Thursday09:00to18:00
Friday09:00to18:00
Saturday24 Hours
Sunday24 Hours

and activate it in Salesforce.

Please advise how it can be achieved in apex?

I have created a REST API to create an object record. But the requirement is only one record can be created at a time since we are using the API for financial application. So if multiple user are hitting the API simultaneously, I need to apply some kind of a queueing mechanism so that only one request will  hit to Salesforce. Is there a singleton mechanism available in Salesforce? Also please provide information on whether object locking is available in Salesforce? Any suggestion on how I can implement the above scenario will be much appreciated.
Hello,
I am trying to build a batch that can be scheduled daily and sends email to all the lead owners if they have any past due date leads.
Each owner should get their own email with an attachment containing only leads assigned to them.
My code below is failing to get an attachment containing only leads assigned to them.
Can any one help me?

global class BatchableLeadEmailAlert  implements Database.Batchable<sObject>, Database.AllowsCallOuts, Database.Stateful {
    global   String  query;
    String YES = 'Yes';   
    //  ---------------------------------------------------------------------
    //  CONSTRUCTOR
    //  ---------------------------------------------------------------------
    global BatchableLeadEmailAlert() {
      query = 'SELECT Id,Name,FirstName,LastName,Phone,Secondary_Lead_Owner__c from Lead where Secondary_Lead_Owner__c != null AND Test_Record__c = \''+YES+'\'';                    
    }    
    //  ---------------------------------------------------------------------
    //  INTERFACE METHOD: start
    //  ---------------------------------------------------------------------
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator(query);
    }
    
    //  ---------------------------------------------------------------------
    //  INTERFACE METHOD: execute 
    //  ---------------------------------------------------------------------
    global void execute(Database.BatchableContext bc, List<sObject> scope) {
    
        Set<Id> userid = new Set<Id>();
        Set<Id> LdId = new Set<Id>();
        for (SObject s: scope) {    
            Lead LdsIds = (Lead) s;  
            LdId.add(LdsIds.Id);
            userid.add(LdsIds.Secondary_Lead_Owner__c);                            
          }     
                    
             List<User> Addresses = new List<User>();
             Addresses = [select Email,LastName from User where Id =: userid];
              List<String> toAddresses = new List<String>();              
              for(User usr: Addresses){
                 toAddresses.add(usr.Email);
              }      
    
          List<Lead> leadlist = [SELECT Id,Name,FirstName,LastName,Phone,Secondary_Lead_Owner__c from Lead where Id =:LdId ORDER BY Secondary_Lead_Owner__c];         
                   
          String header = 'Name, First Name, Last Name, Phone,Secondary_Lead_Owner__c \n';
          String finalstr = header;           
          map<Id, String> userleadsmap = new map<Id, String>();

        for(Lead a: leadlist)
        {                     
               string recordString = a.Name+','+a.FirstName+','+a.LastName+','+a.Phone+','+a.Secondary_Lead_Owner__c+'\n';
               finalstr = finalstr +recordString;               
               userleadsmap.put(a.Secondary_Lead_Owner__c, finalstr);                           
        }             
         List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
            for(User portalUser :Addresses) {
                    Messaging.EmailFileAttachment csvAttc = new Messaging.EmailFileAttachment();
                    if(userleadsmap.containskey(portalUser.Id)){ 
                    blob csvBlob = Blob.valueOf(userleadsmap.get(portalUser.Id));                    
                    string csvname= 'Lead.csv';
                    csvAttc.setFileName(csvname);
                    csvAttc.setBody(csvBlob);
                    }
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    string body = 'Hi '+ portalUser.LastName;
                    String[] ccAddresses = new list<string> {'gvinnakota@ten-x.com'}; 
                    mail.setCcAddresses( ccAddresses );
                    mail.setSubject('Test Subject');
                    mail.setTargetObjectId(portalUser.Id); 
                    mail.setSaveAsActivity(false);
                    mail.setHtmlBody(body); mails.add(mail);
                    mail.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttc});
               }
            Messaging.sendEmail(mails);
             }

   global void finish(Database.BatchableContext bc){       }
}
 
Hello all,

I am struggling to write a Test Class for the following trigger and static class that synchronizes portal users with contact record data:
trigger UpdateContactFromPortalUser on User (after update) {
    //We only want to run on the single item that the user edited 
    if (Trigger.new.size()==1) 
    { 
        User u =_ Trigger.new[0]; 
        //And only if it's a portal user 
        if (u.ContactId!=null) { 
            UpdateContactFromPortalUser.updateContacts(u.Id); 
        } 
    } 
}
global class UpdateContactFromPortalUser { 
    @future 
    public static void updateContacts(String userId) {
        User u = [select ContactId,Email,FirstName,LastName,Title
                    from User
                    where Id=:userId];

        if (u!=null && u.ContactId!=null) {
            Contact c = new Contact(Id=u.ContactId,Email=u.Email,FirstName=u.FirstName,LastName=u.LastName,Title=u.Title);
            update c; 
        }
    }
}
Here is my test class code:
 
@isTest
private class UpdateContactFromPortalUserTest {

static testMethod void testUpdateContacts() {

        Test.startTest(); 
        
        User u = [select Id,ContactId,FirstName from User where ContactId<>'' limit 1]; 

        u.FirstName='Bar';
         
        update u; 

        Test.stopTest(); 

        Contact c = [select FirstName from Contact where Id=:u.ContactId]; 
        System.assertEquals(c.FirstName,u.FirstName); 
    }
}

I am getting no code coverage when I runt the test.  Can someone help point me to what I am missing?

Thanks in advance for any help.

 
We have a catagory of accounts that need to receive an email every 10 days until a checkmark is removed from thier account. I tried using a workflow that triggered the email and delayed the next email. This worked but I ran into a limit on the number of delayed workflow jobs available.

I was thinking of switching this task to something like an Apex Schedualed class that would check for the account bit and send the email. Is this the best way to handle this?

My sudo code would be something like this:
  • (run every day)
  • query for list of accounts that have not received an email in more than 9 days.
  • update the record with something that would trigger an email
  • the tiggered email would update the date of last email

 

Hi all,

I am quite new to triggers. Using the forum I was able to create a trigger to prevent delete based on a picklist value. Now I am trying to write a trigger that will prevent delete based on 'who' the record is Createdby. We do not want users to be able to delete records created by the site user. Unfortunately I am not able to figure this one out. Can anyone help with the code?

Thanks!

trigger  DeleteJobApplication   on  cxsrec__cxsJob_application__c(before delete){
if(system.Trigger.isDelete){
String Userid=[SELECT id,Name FROM User WHERE Id =:UserInfo.getuserid()].Name ;
    for(cxsrec__cxsJob_application__c  J:Trigger.old){
          if(J.Createdby == 'ResourceManager Profile' ){
             J.addError('Je kan de inschrijving niet verwijderen wanneer deze is gemaakt door de site user');
            }
     }
     }
     }

Hi Expert,

On the oppertunity page i want to hide a related list button if oppertunity stage changed.

User-added image
I have a force.com site that sometimes has an unhandled execption, it happens.  Normally I'd just turn on logging for that guest user and see what the people were doing wrong.  After winter '17, users will have to have a special cookie for logs to be created.

My thought was to set this special cookie whenever the user accesses the site.  That way I can just turn on logging when needed.

I see the setCookies method, but that adds the apex__ prefix to the name.  Is there another way?  I'm just an admin code hacker, so forgive me.
  • October 20, 2016
  • Like
  • 0
Hello. I have a situation where, it is required to make an @future callout on Save of a record. And this occurs from the Trigger Handler class. All is good with respect to record getting saved, and the callout being made. However, I want to do something for the scenario where the callout fails at the external system. The DML is already done, so Salesforce data is updated. However external system is out of sync.  Is there any good architecture to handle this situation?   Ideally, values in 2 systems must not go out of sync at any point in time.  If the call out fails, the values in Salesforce should be rolled back.  Any architecture recommendations?
Hi ..
Is there any way that I could export selected rows from a table view ? for example if there is a table with 10 records , I want to export the first , third and fourth (selected with checkbox) ?
I tried to search about it but I'v got no clue .. did I miss something ?
Hi,

I'm developping a push notification system for a mobile application. As thousands of users can access to the mobile application, I'd like to send notifications only to users who have already connected once with the app.
I've seen these informations are displayed in Administration Setup with the ConnectedApp OAuth User's Usage.
I can also get these informations from a Identity Users Report by creating a report type based on User->Identity Event Logs.

My question is, is it possible to get these informations through apex, using api or soql query?

Regards,
Yohann
Hi, 
I have installed the managed package in to my org. here the system admin access all the managed package objects and pages classes, successfully. I have created the community users to set all object permission , i checked  all the objects have deployed mode.they got the tabs once they clicked that tabs means its showing error like "No url longer exist" how to solve this problem.? I need suggestion .
I know there are many other ways to access Salesforce API endpoints than through the AJAX Toolkit Shell.  So, the following problem is not holding me up and shouldn't hold up anybody else.  That being said....

If you try to use the AJAX Toolkit Shell, do you also experience an infinite loop of prompts to login?

Use case:
  1. The help page at https://help.salesforce.com/articleView?id=loader_content.htm&type=5 says to use the AJAX Toolkit Shell.  (Yes, I know there are resources other than the AJAX Toolkit Shell that can be used to get the information that page is directing you to get.)
  2. When I go to the toolkit at https://[my-domain].my.salesforce.com/soap/ajax/45.0/debugshell.html, then Salesforce redirects me to the login page at https://[my-domain].my.salesforce.com/?startURL=/soap/ajax/45.0/debugshell.html. After I log in, Salesforce takes me back to the AJAX Toolkit Shell page, but that page redirects me again to the login page. This loop continues ad infinitum.
The cause for this loop appears to be that the "sid" cookie is inaccessible from Salesforce's Toolkit JavasSript because Salesforce elsewhere flagged the "sid" cookie as "HttpOnly".  (So, the cookie is passed during HTTP/S communication but isn't accessible to the JavaScript.)

Thoughts?  Confirmations?

(Again, I know there are lots of resources available other than the  AJAX Toolkit Shell that work.  This question is solely about whether anybody else is encountering this error with the Tookit itself.)