• jigarshah
  • PRO
  • 2683 Points
  • Member since 2012
  • Enterprise Solution Architect


  • Chatter
    Feed
  • 77
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 1
    Questions
  • 563
    Replies
How do I add a Custome Object to the Opportunity page Layout?
I need it to be a new section - it will be a form to fill out
Hi Team,

I wonder if there's a best practice regarding the following scenario for  going on a for loop inside a for loop for a SOQL query on an object with a sub query. For example:
List<Parent__c> lp = [
  SELECT Id, Name,
    (SELECT Id, Name FROM Child__r WHERE Name = :childFilter)
  FROM Parent__c
  WHERE Name = :parentFilter
];

for(Parent__c p : lp){
  System.debug('Parent__c Name: ' + p.Name);
​  for(Child__c c : lp.Child__r){
    System.debug('Child__c Name: ' + c.Name);
  }
}
Should I build the query on the child level and populate a Map<Id,Child__c> with back references to the parent object attributes, then do a for inside a for loop over map Id, then object? Thanks a lot.
Hello,

I am trying to update a custom number field on a custom object (placement) from a list of a seperate custom objects (timesheets). The following returns no errors, however when I run this through an anonymous window, it doesn't properly update the TCEndDateAudit__c on the Placement object (it turns up null). 

Here is my code so far: 
public class CamstimecardEndDateAudit{
public void auditTimeCards(){
    List<jstcl__TG_Timesheet__c> myList = new List<jstcl__TG_Timesheet__c>();

     myList = [SELECT jstcl__Placement__r.Name, Period__c, jstcl__Placement__r.TCEndDateAudit__c
                            FROM jstcl__TG_Timesheet__c 
                            WHERE jstcl__Placement__r.ts2__Status__c IN ('Active') 
                             AND jstcl__Week_Ending__c = LAST_N_DAYS:15
                             AND jstcl__Status__c = 'Pending' Limit 199];
    
    for(integer i=0 ; i < myList.size(); i++) {
        IF(myList[i].Period__c == 'Weekly Split'){
    myList[i].jstcl__Placement__r.TCEndDateAudit__c = myList[i].jstcl__Placement__r.TCEndDateAudit__c+ 0.5;}
       else{
    myList[i].jstcl__Placement__r.TCEndDateAudit__c = myList[i].jstcl__Placement__r.TCEndDateAudit__c+ 1;
    }
    }
    
  update myList;
}}

 
i saw in documentation maximum batch size is 200. if we enabled bulk Api its is upto 10000 .
But how we can import more than 50000 - 5M records if it exceed the size? please anyone explain the overall dataloader process
  • April 11, 2018
  • Like
  • 0
I have created a simply trigger that adds the values of two currency fields and renders the full amout into a total field.
I need assistance creating a class for this trigger so that I can deploy it

trigger Sum ON order__c(before insert, before update) {

    for (order__c o: Trigger.new) {
        if (Trigger.isUpdate && o.new_total_field__c != Trigger.oldMap.get(o.Id).new_total_field__c) {
            
            continue;       
        }
        o.new_total_field__c = o.hss_qty_price__c + o.sb_qty_price__c ;

    }
}

Any feedback would be greatly appreciated 

Thanks

D
The issue is when I developing my lightning app and changed files and saved/built on the server,
in the same browser and session, I can not get the latest change, even after few hours.
but if I open a new browser and login, I can get my latest change, however if I changed something again, this browser doen't update any more.
then I have to  switch to another brower. I don't have so many browers and every time login needs code challenge.

It's quite annoying and made my developing so inefficient, anyone else got same issue?

I am stuck on Step 3: Add a Battle Station field (Master-Detail Relationship) of the Build the Object Model module. 

Create the Battle Station relationship field as follows:
For Data Type, select Master-Detail Relationship, and click Next.

When I follow these steps, I receive the following error message:

Error - You cannot add a master-detail relationship to a managed custom object

Any suggestions?

The error I am getting is  ERROR:  No such column 'PackageDirectories' on sobject of type ScratchOrgInfo.    

sfdx force:org:create -f  sfdx-project.json -a myorgthing

json file

{
  "packageDirectories": [
    {
      "path": "force-app",
      "default": true
    }
  ],
  "namespace": "",
  "sfdcLoginUrl": "https://login.salesforce.com",
  "sourceApiVersion": "42.0"
}
 

folder structure is 
 

--force-app
  -- main
    -- default
      -- applications
      -- classes
      -- et.all.
 

 

I'm trying to not allow the "," character to be used in a specific field. What I'm currently using below doesn't seem to be working and I'm stuck. 

NOT(REGEX(Address_Line_1__c , "[a-zA-Z0-9$%&]"))
This is my first Apex Class.  I have tried to imlement the Batchable Class given by SalesForce and have the current logic working for a set of records when i execute from Developer's Console using the following:
     Batch_OrderStatus b = new Batch_OrderStatus();
     database.executebatch(b);

Records are updated successfully.  However, will only execute the limit i enter in the query.  I want the code to execute over and over until all records within the Select driver are exhausted.   It has been suggested to move the two Select Count queries into a map and not have them within the FOR loop.  I will try to make that change, but wanted to get clarification on a couple other questions.  I appreciate any direction the community can give me.

1)  What is best way to schedule a  batch process that is going to run daily?  Should I use the Schedule option within SalesForce within Apex Classes?  Add to batch job table?  Or is there a better way?
2)  How can I change my logic so it executes over and over until the initial query has been completed without getting Limit exceptions?  I know there is a better way to do this, but the current code just pulls the first 25 records out of the 300 that are returned in the query.

Following is my current code:

/*
 * @Name: Batch_OrderStatus
 * @Author: Dan Norfleet
 * Updates : February 2018 - Dan Norfleet - Created Apex Class
 */
global with sharing class Batch_OrderStatus implements Database.Batchable<sObject> {
    global final String query;
    public String statusSubmitted = 'Order Submitted';
    public String emailText = '\n ACTION           ORDER                  STATUS\n ------------------------------------------------';
    public List<ccrz__E_Order__c> ordList = new List<ccrz__E_Order__c>();
    public Integer total_orders_cnt = 0;
    public Integer update_received_cnt = 0;
    public Integer update_cancelled_cnt = 0;
    public String status_received = 'Received';
    public String status_order_received = 'Order Received';

    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, name, ccrz__orderstatus__c FROM ccrz__E_Order__c WHERE ccrz__orderstatus__c = \'Order Submitted\'';
        query = query + 'limit 25';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
          // Loop through the list of orders
          for(sobject s : scope)
          { 
            ccrz__E_Order__c ord = (ccrz__E_Order__c)s;
            total_orders_cnt = total_orders_cnt + 1;
            String order_id = ord.Id;
            // For each order, see how many items are in 'Received' status
            integer ItemsReceived = 
                    [SELECT COUNT() 
                    FROM ccrz__E_OrderItem__c 
                    WHERE ccrz__orderitemstatus__c = :status_received
                    AND ccrz__order__c = :order_id];
              
            integer ItemsNOTReceived = 
                    [SELECT COUNT() 
                    FROM ccrz__E_OrderItem__c 
                    WHERE ccrz__orderitemstatus__c != :status_received
                    AND ccrz__order__c = :order_id];
          
            if (ItemsReceived > 0 && ItemsNOTReceived == 0)
                { 
                ord.ccrz__orderstatus__c = 'Order Received';
                update_received_cnt = update_received_cnt + 1;
                emailText = emailText + '\n Updated         ' + ord.Name + '      Order Received';
                }
            else if (ItemsReceived == 0 && ItemsNOTReceived == 0)
                { 
                ord.ccrz__orderstatus__c = 'Cancelled';
                update_cancelled_cnt = update_cancelled_cnt + 1;
                emailText = emailText + '\n Updated         ' + ord.Name + '      Cancelled';
                }
                        else
                                {
                emailText = emailText + '\n No Change     ' + ord.Name + '      Order Submitted';
                                }

          }
          update scope;
          
                  /* E-Mail */
                  //Send an email to the User after your batch completes
    System.debug('    emailText = ' + emailText);
                  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                  mail.ToAddresses  = new string[] {'batch.example@google.com'};
                  mail.setSubject('Apex Batch Job is done');
                  mail.setPlainTextBody(emailText);
                  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }

    global void finish(Database.BatchableContext BC) {
          AsyncApexJob a = [SELECT Id,
                            Status,
                            NumberOfErrors,
                            JobItemsProcessed,
                            TotalJobItems,
                            CompletedDate,
                            ExtendedStatus,
                            ApexClass.name,
                            CreatedBy.Email,
                            CreatedBy.Name
                            FROM AsyncApexJob
                            WHERE Id = :BC.getJobId()];
  
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.ToAddresses  = new string[] {a.CreatedBy.Email};
            mail.setSubject('Async Apex Batch Job Status' + a.ApexClass.name);
    
            string td1 = '"border:1px solid #e6e6e6; width=200px;"';
            string td2 = '"width=200px; border:1px solid #e6e6e6; background-color:#E44905; color:white; font-weight:bold;"';
            string tdHead = '"border:1px solid #e6e6e6; width=200px; color:white; background-color:#9370DB; font-weight:bold;"';
            string ExtendedStatus = '';
            if (a.ExtendedStatus != null)
                ExtendedStatus = a.ExtendedStatus;
            string tdErrors = td1;
            if (a.NumberOfErrors > 0)
                tdErrors = td2;
            string htmlBody = '<div style="border:2px solid #e6e6e6; border-radius:10px; "><p>Hi Team,</p><p><span style="color:brown; font-weight:bolder;">Hallmark Salesforce</span> completed running <b>Apex Batch Code.</p>'
                              + '<p>Results:</p>'
                              + '<center><table style="border:3px solid #e6e6e6; border-collapse:collapse;">'
                              + '<tr><td style=' + tdHead + '>Class Name</td><td style=' + tdHead + '>' + a.ApexClass.name + '</td></tr>'
                              + '<tr><td style=' + td1 + '>Completed Date</td><td style=' + td1 + '>' + a.CompletedDate + '</td></tr>'
                              + '<tr><td style=' + td1 + '>Status</td><td style=' + td1 + '>' + a.Status + '</td></tr>'
                              + '<tr><td style=' + td1 + '>Job Items Processed</td><td style=' + td1 + '>' + a.JobItemsProcessed + ' / ' + a.TotalJobItems + '</td></tr>'
                              + '<tr><td style=' + td1 + '>NumberOfErrors</td><td style=' + tdErrors + '>' + a.NumberOfErrors + '</td></tr>'
                              + '<tr><td style=' + td1 + '>Extended Status</td><td style=' + td1 + '>' + ExtendedStatus + '</td></tr>'
                              + '<tr><td style=' + tdHead + '>Created By</td><td style=' + tdHead + '>' + a.CreatedBy.Name + ' (' + a.CreatedBy.Email + ')</td></tr>'
                              + '</table></center>'
                              + '<p><span style="font-family:"Courier New", Courier, monospace; color:#e6e6e6; font-weight:bold; font-size:larger;">Hallmark Salesforce Admin Team</span></p></div>';
    
            mail.setHtmlBody(htmlBody);
            List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
            mails.add(mail);
            Messaging.sendEmail(mails);
    }
}
Thought that Validation Rules and then Process builder would have the answer here, but I'm not finding the system-wide variable for "Current User" as a valid option for either of those systems so I'm not sure how to set this up.

I have an object that Sales has access to and they can edit a specific field "Recommended to", however I only want them to be able to edit that field when they are the specific record owner.  These records might change owner over and over again in their life-cycle and I wanted to restrict the ability to change that field only to who presently owned it.  Hope I do this with something other than having to scrap the Page Views and put in manual Visualforce code!
Hi All,
I have two object one is Bank__c and another one is customer__c. Customer data I am getting from external system (SAP). From SAP I will select the customers and then I will select the bank to map. All customers will showing everytime. If Customer1 is linked to Bank1 then Customer1 sholud not be allowed to map to another Bank. How can I do this?
Please help me.
Thanks in Advance
Hi All,
I want to prevent duplicate records while saving. I do not want to create trigger for this. I want to do it in apex class. Here is my requirement.
I have two object. one is bank__c and another one is customer__c. both are having master detail. master is bank__c and child is customer__c.
Right now I am saving records as below.
cus.add(new customer__c(bank__c=bankId,accountnum__c=data.num__c));

here data variable is wrapper list that I am assigning to accountnum__c.
I want to prevent duplicate records with duplicate num__c. I dont want to create trigger for this. I want to do changes only apex class.
Please suggest me how to do this.
Please help me.
Thanks in Advance
I have a set which contains some contact IDs and I have a List which contains Contact records, I want to check the list of contacts that are present in the set and do some logic. I am doing it but I feel what I am doing is wrong. Here is the code snippet. I appreciate your help
trigger IMRORevisionTrigger on iMROrevision__c (before insert, before update, after insert, after update) {
    set<id> mvssArray = new set<id>();
    set<id> NomvssACArray = new set<id>();
    set<id> serviceCenterID = new set<id>();
    set<id> aircraftIds = new set<id>();    
    set<id> ImrevisionID = new set<id>();
       
    public datetime Add30Days;
    public list<contact> lstcon;
    public list<contact> lstcon1;
    public list<case> lstCase;
     public list<aircraft__c> lstAir;   
    if(trigger.isUpdate && (trigger.isafter || trigger.isbefore)){        
        for(iMROrevision__c lstimr : trigger.new){
              if(lstimr.aircraft__c != null)                 
                 aircraftIds.add(lstimr.aircraft__c);             
        }
    }
    case cs = new case();
    lstCase = new list<case>();        
    if(aircraftIds.size()>0){
         lstAir = [select id, 
                    (select id, MVSS_Contact__c, status__c from Aircraft_Relationships__r where status__c = 'Delivered'),ServiceCenter__c from aircraft__c where id in: aircraftIds];
       lstcon1 = new list<contact>();     
            for(aircraft__c ac : lstAir ){
                system.debug('the aircraft id----' +  ac.id);
                    for(Aircraft_Relationship__c acRel : ac.Aircraft_Relationships__r){
                        system.debug('the mvss con 0000' + acRel.MVSS_Contact__c );
                        if(acRel.MVSS_Contact__c != null)
                        mvssArray.add(acRel.MVSS_Contact__c);
                        if(acRel.MVSS_Contact__c == null ){
                                NomvssACArray.add(ac.id);
                            }
                    
                         }             
            }             
     }   
    if(mvssArray.size()>0)       
        lstcon = [select name,id,DateMXSurveySent__c from contact where id in : mvssArray ];
        if(trigger.isUpdate && trigger.isafter){
            for(iMROrevision__c i : trigger.new){  
                           
                if(i.NumofInvoices__c == 1 && (!i.IsInternational_ServiceCenter__c)){                   
                    if(mvssArray.size()>0){
                    system.debug('777777777' + i.ServiceCenter__c);                                  
                    map<id, contact> mapMvssCon = new  map<id, contact>();
                    for (contact con : lstcon){
                       mapMvssCon.put(con.id, con); 
                           
                    for(id conID : mvssArray) {
                       if (mapMvssCon.containsKey(conID)){
                           system.debug('---------' + mapMvssCon);
                           system.debug('list contains contact');
                           if(con.DateMXSurveySent__c != null){
                            Add30Days = con.DateMXSurveySent__c.addDays(30);
                            system.debug('30 days --' +  Add30Days);
                            if( Add30Days<System.now() || con.DateMXSurveySent__c == null ){
                                system.debug('the sent date ----- ' + con.DateMXSurveySent__c);               
                                con.SendMXSurveyToContact__c = true;
                                con.SurveyServiceCenter__c = i.ServiceCenter__c;
                                con.SurveyAircraft__c = i.Aircraft__c;
                                system.debug('the checkbox survey---' + con.SendMXSurveyToContact__c);
                                if(i.Cbadge__c != null )                                                            
                                con.CSRid__c = i.Cbadge__c;
                               // lstcon.add(con);
                            	}
                                
                              }
                            }
                         
                         } 
                       update lstcon; 
                      }             
                // update lstcon;              
                    if(NomvssACArray.size()>0){  // create a case if there is no MVSS Contact
                   list<aircraft__c> NoMVssConlstAc = [select id, 
                   (select id,ServiceCenter__r.name, ServiceCenter__c,Cbadge__c,NumofInvoices__c  from iMROrevisions__r),ServiceCenter__c from aircraft__c where id in: NomvssACArray];
                       for(aircraft__c acr :NoMVssConlstAc){                       
                     //  for(iMROrevision__c Imr : acr.iMROrevisions__r){                       
                       
                        Id RecordTypeIdCase = Schema.SObjectType.case.getRecordTypeInfosByName().get('Post MX Survey').getRecordTypeId();
                        cs.Case_Name__c = 'Populate MVSS Contact';
                        cs.Launch_Date__c = system.today();
                        cs.Team_Req__c = 'Aftermarket';
                        cs.Status = 'New';
                        cs.Business_Focus__c = 'Service';
                        cs.Communication_Category__c = 'Promotion';
                        cs.Type = 'Other';
                        cs.recordTypeid = RecordTypeIdCase;
                        cs.Subject = 'Please Add MVSS Contact for AirCraft Relationships' ;
                        cs.ServiceCenterLookup__c = i.ServiceCenter__c;
                        cs.Aircraft__c = i.Aircraft__c;                        
                        system.debug('-----------' + cs);
                        lstCase.add(cs);
                       insert cs;
                        system.debug('case records info'+ lstCase);
                        }    
                        //insert cs;                 
                    }                    
                } 
               
                           
            } 
            
            
            // if(!lstCase.isempty())
              //   insert lstCase;
        }
        
        }  
    
            
}

mvssArray in the code contains contact IDs and lstcon holds the data of all contact IDs present in mvssArray.
map<id, contact> mapMvssCon = new  map<id, contact>();
                    for (contact con : lstcon){
                       mapMvssCon.put(con.id, con);                           
                    for(id conID : mvssArray) {
                       if (mapMvssCon.containsKey(conID)){
this is what I am doing in the code to map the values. Please suggest me if I am missing something.
Thank you
I've been trying to work through this project, but I keep running into this error.  I deactivated and repurposed users, but I can't get the two users working correctly without running into this.  The error tells me to submit a case, but the help site won't let me.  How do I fix this?

Here in visualforce page i have two selectoption dropdownlists.
Account list
Contacts list
In accounts list i'm displaing all salesforce accounts and based on the selected account I'm displaying the related contacts in Contacts list.
After getting the selected contact i'm mapping that contact details to the other custom object.
Req: How to filter the selected contact record from selectedOption list?
This is my apex class:
public with sharing class Picklist{
public String selectedAccId{get;set;}
public String selectedConId{get;set;}
public String selectedContactId{get;set;}
public String firstname;
public String lastname;
public String email;
public String company;
public String mailingcity;
public String mailingstate;
public String mailingcountry;
public String mobileno;
public Status__c login1;
List<System.SelectOption> conOptions{get;set;}
List<System.SelectOption> options{get;set;}
public Picklist(ApexPages.StandardController controller){
this.login1= (Status__c)controller.getRecord();
}
public List<System.SelectOption> accOptions{get;set;}
//getting all salesforce accounts
public List<System.SelectOption> getAccountNames(){
List<System.SelectOption> accOptions= new List<System.SelectOption>();
accOptions.add( new System.SelectOption('','--Select--'));
for( Account acc : [select Id,name from Account] ){
accOptions.add( new System.SelectOption(String.valueOf(acc.Id),acc.name));
} return accOptions;
} //displaying all related contacts based the selectd account record. public List<System.SelectOption> getContactNames(){
List<System.SelectOption> conOptions= new List<System.SelectOption>();
if(selectedAccId != null){
for(contact con : [select Id,name,accountid,FirstName,LastName,email,MobilePhone,MailingCity,MailingState,MailingCountry from contact where accountid=:selectedAccId ]){
conOptions.add(new System.SelectOption(String.valueOf(con.Id),con.name));
System.debug('conOptions:::'+conOptions);
}
}
return conOptions;
}
//how to get the contact record from conatcs list.
public Pagereference getSelectedContact(){
System.debug('Entered Selected contact id...........'+selectedConId );
List<System.SelectOption> options = new List<System.SelectOption>();
if(conOptions.size() > 0){
System.debug('SelectId::::'+selectedConId);
for(Contact con1 : [select Id, name, Account.Name, accountid, FirstName, LastName, email, MobilePhone, MailingCity, MailingState, MailingCountry from contact where id=:selectedConId]){
firstname = con1.FirstName;
System.debug('Entered ContactNames contact id...........'+firstname);
lastname= con1.LastName; System.debug('lastname:::'+lastname);
email = con1.Email;
System.debug('email:::'+email );

}
}
else{ conOptions.add( new System.SelectOption('--None--','--None--')); } return null; } }

Thanks in advancce if anybody having idea please let me know
Hi there,

I'm facing an issue at the step 3 of the Advanced Apex Superbadge, on the Product2New page the List Price is not editable :

User-added image

In the Visualforce page I'm using :
<apex:column headerValue="{!$ObjectType.PriceBookEntry.fields.UnitPrice.label}" >
    <inputField value="{!p.pricebookEntryRecord.UnitPrice}" />
</apex:column>
and in the controller extension class Product2Extension, here is my wrapper :
public class ProductWrapper {
        public Product2 productRecord {get; set;}
        public PriceBookEntry pricebookEntryRecord {get; set;}
        
        public productWrapper() {
            productRecord = new product2(Initial_Inventory__c = 0);
            pricebookEntryRecord = new pricebookEntry();
        }
}
Any piece of advice to get this working ?

Thanks a lot !


 
My query is
List<Order> lstOrder = [SELECT Id,(SELECT Id FROM Attachments),(SELECT Id,PricebookEntry.Product2.Name FROM OrderItems) FROM Order WHERE Id IN :lstId];

I have tried to display using repeat
<apex:pageBlock >
				<apex:repeat value="{!lstOrder}" var="myFeedVar" >
					<tr>
						<td>
							<apex:repeat value="{!myFeedVar.Attachments}" var="item" >
					       		<apex:image value="/servlet/servlet.FileDownload?file={!item}" id="someImage" height="500px" width="500px"/>  
					    	</apex:repeat>
					   	</td>
					   	<td>
					   		<apex:repeat value="{!myFeedVar.OrderItems}" var="item" >
					       		<apex:outputField value="{!item.Product2.Name}">
					    	</apex:repeat>
					   	</td>
				       	<td>
				       		<apex:commandButton value="LIKE"/>
				       	</td>
				   </tr>
				    
				    <br/><br/>
				</apex:repeat>	
	       	</apex:pageBlock>

I am unable to display OrderItems in repeat. 
When I try to deploy on my production environment I receive the following error message:
Apex CPU time limit exceeded and An unexpected error has occurred. Your development organization has been notified.
The last method in stacktrace where the error happens is my custom method.

I presume that the error is due to the fact that some of the other methods is taking considerable amount of time to be executed.

Please advise how to realize which is the method that is trowing such error and is consuming the entire cpu time.

Please advise how to avoid such error because I really need to find a solution as every time I try to deploy on production I receive such error message:

Apex CPU time limit exceeded and An unexpected error has occurred. Your development organization has been notified.
 
Hello,

I have complete both requirements of PD 2 certificate, MCQ and Trailhead Badges. I have also linked my Webassessor account with trailhead account. It has been almost one week and I am still waiting for my certificate. I have raised mutiple cases for this but no response. My questions are :

1) Is it common for certificate to arrive late or is it just my case, please let me if anyone of you faced similar situation.
2) Is there any way to reach certificate team apart from guided help on the website.

Also any guess why does it take so long to award this certificate, once you have completed all the requirements. For example in case of proctored exam the certificate is awarded immediately. 

Best Regards,
Rahul

I am facing an issue while performing Apex REST integration. I am using the following piece of code to expose my Apex method as a REST Service which another entity can post data to. My code is as follows

 

@RestResource (urlMapping ='/postlead/*')

global class HttpPostHandler{

 

    @HttpPost

    global static void handleHttpPost(){

             

       //Code to create a new record          

    }

}

 

Another application would perform an Http Post to my Apex REST URL however it does not involve any code and only allows configuration of parameters required to achieve a successful post to the below mentioned REST URL. I have configured the following attributes on the application that would be performing the Http Post to my Apex REST functionality.

 

Endpoint URL:  https://<salesforce.com instance>/services/apexrest/postlead

 

Credentials: Username /Password for my sfdc org

 

Header Parameters:  None

 

However when the application performs a Http Post the following error message is returned by SFDC.

[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]


I tried performing a little RnD and also found certain other posts on the Salesforce discussion boards which suggest that we

need to add an OAuth token as a header to the http post request.  My issues are:

 

  1. How do we get the value of the OAuth token that needs to be passed?
  2. How should it exactly be passed in the Http Header?
  3. Are there any other parameters that are required to be passed in the Http Headers to achieve a successful Http Post? If yes, then what are they, what values should be given for each param and how to pass them?

 

Please suggest.

Hello all, 

I am trying to correct an error in  my test class which states 'System.NullPointerException: Attempt to de-reference a null object'. The two lines where I'm receiving error are in the test class -  AccountActiveProducts.updateAccounts(listAssets); and in the class 
 List<Account> accountsToUpdate = new List<Account>();
Which object isn't being instantiated? Below are the classes. Thank you for your help. 

Test Class 

@isTest 

public class AccountActiveProductsTest {
    
    @isTest static void RollupAsset(){
        List<Asset> listAssets = new List<Asset>();
        Set<String> assetSet = new Set<String>();
        Account aTest = new Account(name='Test Acct', billingcity='test', billingstate='Maryland');
        insert aTest;
        //create asset
        Asset asset = new Asset(name = 'Asset 1', AccountId = aTest.Id, ProductFamily__c = 'Bed Stat', Status = 'Shipped' );
        insert asset;
        List<Account> listAccounts = new List<Account>();
        List<Account> listAccountstoUpdate = new List<Account>();
        
        Integer numAssets;
        for(Integer i=0; i<200; i++){
            Asset ast = new Asset(Name = 'Test Asset' + i, AccountId = aTest.Id, ProductFamily__c = 'Bed Stat', Status = 'Shipped');
               if(ast.Status != 'Retired' || ast.Status != 'Obsolete'){
            assetSet.add(ast.ProductFamily__c);
        }
            listAssets.add(ast);
          
        }
        insert listAssets;
        
        Set<Id> ParentIds = new Set<Id>();
        ParentIds.add(asset.AccountId);
        
        assetSet.add(asset.ProductFamily__c);
        
        listAccounts.add(aTest);
        Map<Id, Account> mapAccount = new Map<Id, Account>([Select Id, ProductsOwned__c, (Select Id, ProductFamily__c, Status from Assets Where  (Status != 'Retired' OR Status != 'Obsolete' OR Status != null)) From Account Where Id In: ParentIds]);  
        List<String> assetList = new List<String>();
        assetList.addAll(assetSet);
        test.startTest();
        AccountActiveProducts aap  = new AccountActiveProducts();
        listAssets.add(asset);
        asset.ProductFamily__c = 'Communication Director';
       String productFamily = string.join(assetList,', ' );
           if(aTest.ProductsOwned__c != productFamily){
                       aTest.ProductsOwned__c = productFamily;
                   listAccountstoUpdate.add(aTest);
                   }
        
          if(!listAccountstoUpdate.isEmpty()){
                   upsert listAccountstoUpdate;
               }
       
        if(listAssets.size() > 0){
             update listAssets;
       AccountActiveProducts.updateAccounts(listAssets);
        }
        upsert listAccounts;
        test.stopTest();
    }

}

Class

public class AccountActiveProducts {
    
        public static void updateAccounts(List<Asset> assetLists){
            Set<String> setAssetsToRemove = new  Set<String>();
            List<String> listAssetsToRemove = new List<String>();
            Set<Id> ParentIds = new Set<Id>();
            for(Asset asset:assetLists){
                ParentIds.add(asset.AccountId); 
            }                                            
            Map<Id, Account> mapAccount = new Map<Id, Account>([Select Id, ProductsOwned__c, (Select Id, ProductFamily__c, Status from Assets Where  (Status != 'Retired' OR Status != 'Obsolete' OR Status != null)) From Account Where Id In: ParentIds]);                                                   

            List<Account> accountsToUpdate = new List<Account>();
   
           
            
           if(Trigger.isInsert || Trigger.isUpdate){ 
               for(Account ac : mapAccount.values()){
  
                   List<String> assetList = new List<String>();
                   Set<String> assetSet = new Set<String>();
                   
                   for(Asset accountAsset: ac.assets){
                       if(accountAsset.Status != 'Retired' || accountAsset.Status != 'Obsolete' ){
                       assetSet.add(accountAsset.ProductFamily__c);
                       }
                       
                       if(accountAsset.Status == 'Retired' || accountAsset.Status == 'Obsolete'){
                          
                          assetSet.remove(accountAsset.ProductFamily__c);
                       }
                       
                   }
                   assetList.addAll(assetSet);
                   assetList.sort();
                   String productFamily = string.join(assetList,', ' );
                   
                   if(ac.ProductsOwned__c != productFamily){
                       ac.ProductsOwned__c = productFamily;
                   accountsToUpdate.add(ac);
                   }
               }
               
              //End of for loop above
              
          
               
               if(!accountsToUpdate.isEmpty()){
                   upsert accountsToUpdate;
               }
           }
            
  
            }

}
  • April 30, 2019
  • Like
  • 0
Hello!

We have made programs in the past that allow users to upload CSVs and import data. (But for a specific object, and a specific set of fields). If you know the object, and the format of the CSV, its very simple to represent your data as a pageblocktable. (Set values in column 1 to Account.Name for example)

However, in this case, is it possible to upload a CSV and represet the data as a pageblock table but for an unknown object/unknown set of fields? 

 
How do I add a Custome Object to the Opportunity page Layout?
I need it to be a new section - it will be a form to fill out
Unable to add apex classes in the trial version. The option is disabled. Also Apex triggers .
Hi all,

I am using HTML code in a flow to redirect users to a URL they require to be like this:

"https://link.com/erp/list-view;ordnr...

the html code is:

<a href="https://link.com/erp/list-view;ordnr...

Now when the user click the link, the following URL is being displayed for them:

"https://link.com/erp/list%E2%80%90view;ordnr...

So  the hyphen is not being displayed correctly.

Is there a way to amend this? They want the hyphen definitely so I can not do anything here but to display the URL like they want with the hyphen.
Hi Team,

I wonder if there's a best practice regarding the following scenario for  going on a for loop inside a for loop for a SOQL query on an object with a sub query. For example:
List<Parent__c> lp = [
  SELECT Id, Name,
    (SELECT Id, Name FROM Child__r WHERE Name = :childFilter)
  FROM Parent__c
  WHERE Name = :parentFilter
];

for(Parent__c p : lp){
  System.debug('Parent__c Name: ' + p.Name);
​  for(Child__c c : lp.Child__r){
    System.debug('Child__c Name: ' + c.Name);
  }
}
Should I build the query on the child level and populate a Map<Id,Child__c> with back references to the parent object attributes, then do a for inside a for loop over map Id, then object? Thanks a lot.
Hi, 

  In below method I am using two for loops inside which is a nested for loop. Code is working as expected but the only issue I see is that this might hit into performance issue when there are bulk operation Please suggest me any alternative way to overcome this issue in the code. 
public static void processOptySharingOppTeam(List<Opportunity> newLst) {
     list<id> OpptIds = new list<id>();
     list<OpportunityTeamMember> Otmlst = new list<OpportunityTeamMember>();
 
     for(Opportunity opp : newLst) {
       OpptIds.add(opp.id); 
      }

  for(Opportunity Op : [select id,name,account.Ultimate_Account__c,partner_account__r.Ultimate_Account__c
                        from opportunity where id in :OpptIds]) {  
            system.debug('Opportunity Name ' + Op.name + '   ' + Op.id);
            
        // Account                             
    for(Opportunity_Sharing__c Ops : [select id, Account_Names__c, Key_Text__c, Partner_Account_Names__c,
                                          User__c,Access_Level__c,Global_Account_Rep__c,Top_Account_ID__r.id, Top_Partner_Account_ID__r.id,
                                          User__r.name
                                          from Opportunity_Sharing__c
                                          where   
                                          Top_Account_ID__r.id <> NULL AND
                                          Top_Account_ID__r.id = :op.account.Ultimate_Account__c]){
                                         
                                
     
               if(Ops.User__c <> null && Ops.Access_Level__c <> null){
                  system.debug('Opportunity Sharing ' + Ops.User__r.name); 
                OpportunityTeamMember otm = new OpportunityTeamMember(OpportunityId = op.id,UserId=Ops.User__c,OpportunityAccessLevel=Ops.Access_Level__c
                                                                              ,TeamMemberRole='Global Account Shared Owner'  ); 
              Otmlst.add(otm);           
             }
         }
      
      // Partner Account                        
      for(Opportunity_Sharing__c Ops : [select id, Account_Names__c, Key_Text__c, Partner_Account_Names__c,
                                            User__c,Access_Level__c,Global_Account_Rep__c,Top_Account_ID__r.id, Top_Partner_Account_ID__r.id,
                                            User__r.name
                                     from Opportunity_Sharing__c
                                     where
                                     Top_Partner_Account_ID__r.id <> NULL AND 
                                     Top_Partner_Account_ID__r.id = :op.partner_account__r.Ultimate_Account__c]){
                                         
                                
     
              if(Ops.User__c <> null && Ops.Access_Level__c <> null){
                 system.debug('Opportunity Sharing ' + Ops.User__r.name); 
               OpportunityTeamMember otm = new OpportunityTeamMember(OpportunityId = op.id,UserId=Ops.User__c,OpportunityAccessLevel=Ops.Access_Level__c
                                                                              ,TeamMemberRole='Global Account Shared Owner'  ); 
              Otmlst.add(otm);           
            }
         }                    
         
      if(!Otmlst.Isempty()){ 
        upsert Otmlst; 
      }        
    }
  }

Thanks
Sudhir
set<string>mEmpId = new set<string>();
map<string,id> MEmpIds = new map<string,id>(); 
list<Contact> con = [SELECT id,eid,AccountId, from Contact where (eid__c IN :mEmpId);
  for(Contact c : con)
        {
             if(mEmpId.contains(m.eid__c) 
            {
                MEmpIds.put(m.eid__c, c.Id);
            }
        }

how to use map of map for map<id,map<string,id>> MEmpIds = new map<string,id>();  and validate the put is from respective account id
I want to build a custom implementation using the Live Agent API, but I've yet to figure out how to get information about a chat request made by a visitor, and to trigger Apex once a request is made. Is this something that can be accomplished with Process builder or Visitor trigger?
I am new to trailhead so I started with the trailhead playground management and already I have encountered some difficulty on the third module.  I am able to view my installed package in classic mode but not in Lightning and thus it is showing that I have not completed the hand-on assignment.  Can someone please help.  Thanks!
I am able to manully schedule a backup in salesforce. When the backup is ready, salesforce sends a link and a mail to inform me that the backup is ready. Hence, I would have to follow the link to download the backup to my own storage area. 

Is it possible to automate the process where by I don't have to manully download the backup file when it is ready but to automate this process?

Please any guide to give me a headstart? what do i look for what do i use?

Thank you
Steve
Hi,

Just in case this helps somebody! It tooks quite a bit of time to track this issue down.

We've had an issue with the sfdx force:data:tree:import command failing with a MALFORMED_ID message when trying to resolve references during data imports.   It turns out the issue was realated to our namespace, which has numbers in it, which the sfdx tool didn't handle.  
 
An example is :-

plan.json
 
[
    {
        "sobject": "i42as__testParent",
        "saveRefs": true,
        "files": [
            "parent.json"
        ]
    },
    {
        "sobject": "i42as__testChild",
        "resolveRefs": true,
        "files": [
            "child.json"
        ]
    }
]

parent.json 
 
{
    "records": [
        {
            "attributes": {
                "type": "i42as__testParent__c",
                "referenceId": "parentRef1"
            },
            "i42as__Message": "Hello"
        }
    ]
}

child.json
{
    "records": [{
        "attributes": {
            "type": "i42as__testChild__c",
            "referenceId": "testChildRef1"
        },
        "i42as__parent__c": "@parentRef1"
    }]
}

When run with the following command, this returns an error.  
 
sfdx  force:data:tree:import --plan plan.json

STATUSCODE    MESSAGE                                                                    FIELDS
────────────  ─────────────────────────────────────────────────────────────────────────  ───────────────────────────
MALFORMED_ID  Object: id value of incorrect type: @parentRef1  i42as__parent__c
=== testChildRef1 [1]

In turns out this was an error in the salesforce-alm library, the regex used to look for the @parentRef1 replacement was not expecting a number in the namespace.  I've managed to work around the issue by changing the file .local/share/sfdx/client/node_modules/salesforce-alm/dist/lib/data/dataImportApi.js as follows;-
 
const jsonRefRegex = /[.]*["|'][A-Z_]*["|'][ ]*:[ ]*["|']@([A-Z0-9_]*)["|'][.]*/igm;
const jsonRefRegex = /[.]*["|'][0-9A-Z_]*["|'][ ]*:[ ]*["|']@([A-Z0-9_]*)["|'][.]*/igm;



 
Hi there,

We are looking for talented SF developers (various positions)

If you are looking for fresh new challenges, do get in touch with me.

Thanks
Tin