• Timo Bierbrauer
  • NEWBIE
  • 30 Points
  • Member since 2017

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 7
    Likes Given
  • 0
    Questions
  • 7
    Replies
I would like to create a lookup relationship to a parent object using the parents external id from a before insert/update trigger. I am not receiving an error when I do this, but it is not creating the relationship. I have tested using anonymous apex with a dml and the code works fine. In the example, Tech1_ID__c is the external id of the Property__c object. 
trigger CaseAddressHandler on Case (before insert, before update) {
for(Case c: trigger.new){
  c.Property__r = new Property__c(Tech1_ID__c =c.Property_Id__c); 
  }
}
I would like to create a lookup relationship to a parent object using the parents external id from a before insert/update trigger. I am not receiving an error when I do this, but it is not creating the relationship. I have tested using anonymous apex with a dml and the code works fine. In the example, Tech1_ID__c is the external id of the Property__c object. 
trigger CaseAddressHandler on Case (before insert, before update) {
for(Case c: trigger.new){
  c.Property__r = new Property__c(Tech1_ID__c =c.Property_Id__c); 
  }
}
Hello all,
I'm getting the error in subject when I try to run this code:
@auraEnabled(cacheable=true)
public static void Equalize(string campaignsStr){
    string[] campaigns = (string[])JSON.deserialize(campaignsStr, list<String>.class);

    //Will hold the opportunities to update
    list<opportunity> updates = new list<opportunity>();

    //Will keep track of user ids and opp counts
    map<string, integer> owners = new map<string, integer>();	//String = OwnerID	Integer = opp count

    list<opportunity> opps = [SELECT Id, OwnerId FROM Opportunity WHERE Primary_Campaign_Filter__c IN :campaigns LIMIT 9999];
    System.debug('opps size: ' + opps.size());

    //Initializing the values of the owners map
    for(opportunity o: opps){
        if(owners.containsKey(o.ownerID)){
            owners.put(o.ownerID, owners.get(o.ownerID) + 1);
        }
        else{
            owners.put(o.ownerID, 1);
            System.debug('Adding owner ' + o.ownerId);
        }
    }

    //For each opportunity, if that owner already has more than the average,
    //give it to the person with the lowest opportunity count.
    integer threshold = opps.size()/owners.size() + 2;
    for(opportunity o: opps){
        if(owners.get(o.OwnerID) > threshold){
            string lowest = GetLowest(owners);
            owners.put(o.OwnerID, owners.get(o.OwnerID) - 1);
            owners.put(lowest, owners.get(lowest) + 1);
            o.OwnerID = lowest;
            updates.add(o);
        }
    }

    //PULL MY DEVIL TRIGGER
    System.debug('updates size: ' + updates.size());
    try{update updates;}
    catch(exception e){
        System.debug('exception: ' + e);
    }
}
I have seen solutions for Lightning Components (like https://developer.salesforce.com/forums/?id=906F0000000917DIAQ), but none that apply to Lightning Web Components. This is part of a component that has multiple other apex methods being called, and they all update fine.

Can anyone help me identify where the problem is?

Thanks!
 
In toast message its showing long text message without breaking the line and its showing same line.
just i need to break the message and show in toast meessage.
Hi All, 

I'm currently trying to use a REGEX operator in a formula field. This is my code : 

IF(
  OR(
    REGEX((SUBSTITUTE(Contact_Phone__c," ","")), "[0-9]{12}"),
    REGEX((SUBSTITUTE(Contact_Phone__c," ","")), "[0-9]{11}")
    ),
  SUBSTITUTE(Contact_Phone__c," ",""),
  ""
  )

This is the error I get : Function REGEX may not be used in this type of formula (Related field: Formula)

But on the documentation page (https://help.salesforce.com/articleView?id=customize_functions_i_z.htm&type=5) it seems like I can use REGEX in a formula field. 

Many thanks for any explanation !
Hello, I created a trailmix (URL: https://trailhead.salesforce.com/users/00550000006wCAnAAM/trailmixes/), define it as public but my team's members can't access it (Salesforce internal team). Any idea?
Thansk in advance
Hi All,

I could use some guidance on how to properly parse my JSON into a custom object. I am able to get all of my deserialized results in the debug log, but I am not able to access individual variables to create a new object and populate the fields. I can get top level object results, but not individual member data like myMap.get('specificVariable');

Full code:
public class NPIcalloutHelper {
    
    public static String getDocById(Integer NPIid){
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://npiregistry.cms.hhs.gov/api/?number='+NPIid);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        String strResp = '';
        
           system.debug('******response '+response.getStatusCode());
           system.debug('******response '+response.getBody());
        
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) 
        {
            // Deserializes the JSON string into collections of primitive data types.
           Map<String, Object> npiResults = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            // Cast the values in the 'results' key as a list
            List<Object> allresults =(List<Object>)npiResults.get('results');
            System.debug('allresults' + allresults );
                   }
        return strResp ;
   }

}

 

Hey all,

 

This is one of those questions when I feel like I'm probably going about a simple process the wrong way and over complicating it, but I'm not sure the alternative. So I'll ask my question and if you have a better approach, please feel free to share.

 

The deal is that I have an Apex REST service that allows a user to pass in an object type, and any field values in the URL.

EX : http://na2.salesforce.com/apex/reservice/contact?firstname=frank&lastname=jones&age__c=21

 

My code works fine for any string values, but chokes on numerics. Because I instantiate a new instance of the type of object they pass in, then I loop over all the fields in the query string and dynamically add them to the sObject. Of course as far as apex is concerned all those arguments in the query string are in fact strings, so when adding non string things to the sObject it explodes. 

 

Ideally I could use the get describe info about the field I'm inserting to find it's type and cast the value to be inserted to the correct type, but as far as I know there isn't a way to do dynamic casting at runtime. A series of if statments is about the only alternative I see, but that feels really dirty. 

 

This is what I have currently (you can see I'm kind of using the if statment path, trying to make it as simple as possible).

 

Just to be clear, this code works, it's just not as efficient/dynamic as I'd like.

 

    public static sObject saveSObject(string objectType, string recordid, RestRequest req)
    {
        //create a generic sObject to contain the update values.
        sObject updateObj;      
                
        //get the describe object for the type of object passed in (its just passed in as a string from the URL)
        Schema.sObjectType objectDef = Schema.getGlobalDescribe().get(objectType).getDescribe().getSObjectType();
        
        //find all the fields for this object type
        Map<String, Schema.SobjectField> ObjectFieldsMap = objectDef.getDescribe().fields.getMap();
        
 
        //this method can handle updates or inserts. If a record ID was passed in, 
        //cast the object as the type represented by the ID. If not, just create a
        //new object of the type found in the object describe.
        if(recordId != null)
        {
            updateObj = objectDef.newSobject(recordid);
        }
        else
        {
            updateObj = objectDef.newSobject();
        }    
        // populate the object's fields by looping over all the params in the rest request.
        for (String key : req.params.keySet())
        {
            // only add params if they are valid field on the object
            if (ObjectFieldsMap.containsKey(key))
            {
                //figure out the type of this field so we can cast it to the correct type
                string fieldType = ObjectFieldsMap.get(key).getDescribe().getType().name().ToLowerCase();
                
                //since I don't know how to do, or if it's even possible to do dynamic casting we need a 
                //series of if statments to handle the casting to numeric types. I think all the others should
                //be fine if left as a string. Dates might explode, not sure.
                
                
                if(fieldType == 'currency' || fieldType == 'double' || fieldType == 'percent' || fieldType == 'decimal' )
                {
                    updateObj.put(key, decimal.valueOf(req.params.get(key).trim())); 
                }
                else if(fieldType == 'boolean')
                {
                    updateObj.put(key, Boolean.valueOf(req.params.get(key))); 
                }                   
                else if(fieldType == 'date')
                {
                    updateObj.put(key, date.valueOf(req.params.get(key))); 
                }                
                else
                {
                    updateObj.put(key, req.params.get(key));
                }
            }
            else
            {
                system.debug('Invalid field: '+ key + ' for object type ' + objectType);
            }
        }
        //update/insert the object
        upsert updateObj;
        
        //return the saved object.
        return updateObj;
        
    }

 

I would like to create a lookup relationship to a parent object using the parents external id from a before insert/update trigger. I am not receiving an error when I do this, but it is not creating the relationship. I have tested using anonymous apex with a dml and the code works fine. In the example, Tech1_ID__c is the external id of the Property__c object. 
trigger CaseAddressHandler on Case (before insert, before update) {
for(Case c: trigger.new){
  c.Property__r = new Property__c(Tech1_ID__c =c.Property_Id__c); 
  }
}
Hi,

I'm currently working through the Data Integration Specialist superbadge and my attempt throws the following error when I check the challenge:

Challenge Not yet complete... here's what's wrong:
The 'ProjectRESTService' Apex REST service does not appear to be using a SavePoint to rollback change when an exception occurs.

I don't really understand this error as I appear to have implemented a SavePoint for rolling back changes, so any suggestions would be much appreciated.
 
@RestResource(urlMapping='/project/*')
global with sharing class ProjectRESTService {  
	@HttpPost
	global static String postProjectData(String projectRef, String projectName, String opportunityId, Date startDate, Date endDate, Double amount, String status) {                  	                                         
		List<Project__c> projects = [
			SELECT ProjectRef__c, Name, Opportunity__c, Start_Date__c, End_Date__c, Billable_Amount__c, Status__c
			FROM Project__c
			WHERE ProjectRef__c=:ProjectRef
		];
		
		Project__c project = new Project__c();                                 
		if (!projects.isEmpty()) {
			project = projects[0];
		}
                                                 
		project.ProjectRef__c = projectRef;
		project.Name = projectName;
		project.Opportunity__c = opportunityId;
		project.Start_Date__c = startDate;
		project.End_Date__c = endDate;
		project.Billable_Amount__c = amount;
		project.Status__c = status;
		       
		Opportunity opp = [SELECT Id, DeliveryInstallationStatus__c FROM Opportunity WHERE Id=:opportunityId];         
		opp.DeliveryInstallationStatus__c = 'In Progress';
             
		Savepoint sp = Database.setSavepoint();
		try {           
			upsert project;
			update opp;
			return 'OK';  
		} catch(Exception e) {
			Database.rollback(sp);
			return e.getMessage();
		}        	
	}
}

Thanks.
Hi Guys,

I have created hyperlink formula field in detail page, onclick of field should open link in new tab on lighning experience 

Formula Ex:
HYPERLINK("https://ap4.lightning.force.com/apex/KnowledgeArticleInternalApp", "Article","_blank")

Above Formula is Not opening in new tab instead opening in same lightning experience Tab, Any solution is highly appreciated 

Thanks in Advance
 
Hi there,
I want to use showToast and
show message with multiple lines.
I tried as follow but \n is not working well.
({
    fireToastEvent : function(component, event, helper) {
        var toastEvent = $A.get("e.force:showToast");    
        toastEvent.setParams({
            "title": "Title",
            "message": "This is line 1. \n This is line 2. \n This is line 3.",
            "type": "success"
        });
        toastEvent.fire();
    }
})
is there any idea?

Regards,
LinThaw
 
Hello Reader

I  have a Custom object  (called API_Order__c) which has  lookup  field to Account
My plan is  to insert  MULTIPLE  records  in 1  REST API call and I am trying to build  the good JSON
I am not able to do this. I tried  the stanbdard REST  and I tried  to  use the COmposite/tree  REST

Seee below what I havew tried:

TEST 1

I want to  create  1 record  using REST command AND I want to reference the Account with External ID.
I use the below  REST
Method: POST
URL: /services/data/v39.0/sobjects/API_Order__c/

{
  "SourceFile__c" : "DE_1A_MSV3",
  "Order_Date__c" : "2017-07-07",
  "Account__r" : 
         {
         "External_ID_vod__c":"WDEF01663170"
         },
  "Account_Name__c" : "Adler-Apotheke",
  "NumberOfExpectedItemLines__c" : "2", 
  "External_Id__c" : "API_O_1003"
}

this is WORKING

​TEST 2
BUT  if I want to insert  MULTIPLE  records  I do not  know  what is  the right syntax


[
{
  "SourceFile__c" : "Value 1",
  "Order_Date__c" : "2017-07-07",
  "Account__r" : 
         {
         "External_ID_vod__c":"XXXX"
         },
  "External_Id__c" : "API_O_1003"
},
{
  "SourceFile__c" : "Value 2",
  "Order_Date__c" : "2017-07-08",
  "Account__r" : 
         {
         "External_ID_vod__c":"YYYY"
         },
  "External_Id__c" : "API_O_1003"
}
]

I god  JSON parsng ERROR

TEST 3

I tried to use  the COMPOSITE  REST  call  to insert Multiple records and if I am passing the Salesforce ID  of  the  Account lookup is OK 

POST
/services/data/v39.0/composite/tree/API_Order__c

{
"records" :[
  {
  "attributes" : {"type" : "API_Order__c", "referenceId" : "ref1"},
  "SourceFile__c" : "DE_1A_MSV3",
  "Order_Date__c" : "2017-07-07",
  "Account__c" : "0015E000004jH2I"
  }, 
  {
  "attributes" : {"type" : "API_Order__c", "referenceId" : "ref2"},
  "SourceFile__c" : "Val2",
  "Order_Date__c" : "2017-07-07",
  "Account__c" : "0015E000004jH2I"
   }]
}

TEST 4
BUT IF  I TRY  TO REFERENC ETHE ACCOUNT WITH EXTER NAL ID  I FAIL

POST
/services/data/v39.0/composite/tree/API_Order__c

{
"records" :[
  {
  "attributes" : {"type" : "API_Order__c", "referenceId" : "ref1"},
  "SourceFile__c" : "DE_1A_MSV3",
  "Order_Date__c" : "2017-07-07",
  "Account__r" : 
         {
         "External_ID_vod__c":"WDEF01663170"
         },
  "Account_Name__c" : "Adler-Apotheke",
  "NumberOfExpectedItemLines__c" : "2", 
  "External_Id__c" : "API_O_1001"
  },
  {
  "attributes" : {"type" : "API_Order__c", "referenceId" : "ref2"},
  "SourceFile__c" : "DE_1A_MSV3",
  "Order_Date__c" : "2017-07-07",
  "Account__r" : 
         {
         "External_ID_vod__c":"WDEF01663170"
         },
  "Account_Name__c" : "Adler-Apotheke",
  "NumberOfExpectedItemLines__c" : "2",
  "External_Id__c" : "API_O_1002"
   }]
}

I have the ERROR  message: Cannot reference a foreign key field Account__r.


Any help?  

Thanks in advance Csaba
Hi All,

I get the following error when attempting to check in this challenge.  However, if I test my code from workbench, it works correctly.  I've checked my spelling, order of parameters in the method signature.

Challenge Not yet complete... here's what's wrong: 
The 'ProjectRESTService' Apex REST service does not appear to be working properly. Calling the service either didn't update the opportunity correctly, return the string 'OK', create an associated project correctly or function correctly in general.

I've checked other forum post and I noticed people are searching for the project record prior to upserting it.  I don't understand why that is needed if I can upsert directly against the ProjectRef__c external id field.  I could try to copy and paste what they did to pass the challenge, but I want to understand why what I coded doesn't work.  A second pair (or more) eyes would be appreciated.  Thank you!
 
@RestResource(urlMapping='/project/*')
global with sharing class ProjectRESTService {
    @HttpPost
    global static String postProjectData(String ProjectRef, String ProjectName, String OpportunityId, Date StartDate, Date EndDate, Double Amount, String Status) {
		SavePoint sp = Database.setSavepoint();
        
        try {
	        Project__c p = new Project__c(ProjectRef__c=ProjectRef, Name=ProjectName, Opportunity__c=OpportunityId, Start_Date__c=StartDate, End_Date__c=EndDate, Billable_Amount__c=Amount, Status__c=Status);
    	    upsert p ProjectRef__c;
            Opportunity o = new Opportunity(Id=OpportunityId, DeliveryInstallationStatus__c='In Progress');
            update o;
        	return 'OK';
        } catch (Exception e) {
            System.debug('~~~ Cause: ' + e.getCause() +  ' Message: ' + e.getMessage() + ' getLineNumber: ' + e.getLineNumber() + ' StackTrace: ' + e.getStackTraceString() + ' Type: ' + e.getTypeName());
            Database.rollback(sp);
            return e.getMessage();
        }     
    }
        
}

 
Hi All,

I have a required where i need to create Account with Contact and attachment under the contact.
I also need to refer a look up value(Test_Rec_Type_Object__c) on Account with the help of external id and the same with contact as well. On contact i have a look up(Test_Object__c) which i need to refer with the external id.

Here is the snippet which i used from workbench REST API...
----------------------
/services/data/v37.0/composite/tree/Account

{
"records" :[{
    "attributes" : {"type" : "Account", "referenceId" : "ref1"},
    "name" : "Acc with Con with Att New",
    "phone" : "1234567890",
    "website" : "www.salesforce.com",
    "numberOfEmployees" : "100",
    "industry" : "Banking",
    "Test_Rec_Type_Object__c" : {
       "Text_External_Unique__c" : "12345" },

    "Contacts" : {
      "records" : [{
         "attributes" : {"type" : "Contact", "referenceId" : "ref2"},
         "lastname" : "Smith",
         "Title" : "President",
         "email" : "sample@salesforce.com",
         "Test_Object__c" : {
            "TO_External_Obj__c.Id" : "67890" },

    "Attachments" : {
      "records" : [{
         "attributes" : {"type" : "Attachment", "referenceId" : "ref3"},
         "Name": "TestPDF.pdf", 
         "body": "Attach with Rec Creation"
         }]
      }
         }]
      }
    }]
}

Here is the error i am getting... Could any one please help on this... There is some problem in referencing the external id(Highlighted bold)

Cannot deserialize instance of reference from START_OBJECT value { or request may be missing a required field at [line:8, column:27]