Get Salesforce Id of new row in model

  • 1
  • Question
  • Updated 3 years ago
  • Answered
I'm creating a new row on an empty model in JavaScript, and would like to retrieve the Salesforce Id of the newly created row. Here's what I'm doing, "m" is the model:

m.createRow();

m.save();
r = m.getFirstRow();
alert(r.Id);


The new row is being saved to the Salesforce object successfully. However the Id I get is "1", which I gather is a Skuid temporary Id for the row. How can I get the real Salesforce Id? I need it to use in other new rows that will reference my new row.

I've tried doing this:
skuid.model.updateData([m]);
after my save thinking it might retrieve the Salesforce Id, but it throws this error :

"Uncaught Model 'm' has unsaved changes. To update this model's data, you must first save or cancel the changes."
Photo of Ryan Paddy

Ryan Paddy

  • 306 Points 250 badge 2x thumb

Posted 5 years ago

  • 1
Photo of Zach McElrath

Zach McElrath, Employee

  • 49,056 Points 20k badge 2x thumb
Hi Ryan,

You are very close! The trick here is that the save operation is asynchronous, so it will not be completed by the time that you call m.getFirstRow(). What you need to do is to wait until the save is finished, by utilizing a callback function:



m.createRow();
m.save({callback: function(result){
if (result.totalsuccess) {
r = m.getFirstRow();
alert(r.Id); // should be a real SF Id now
} else {
// There was a problem. Let's see what went wrong.
console.log(result.insertResults[0]);
}
}});
Photo of Rajendra Rathore

Rajendra Rathore

  • 1,480 Points 1k badge 2x thumb
Hi Zach,

We are using "6.8.19" version.

Thanks
Photo of Rajendra Rathore

Rajendra Rathore

  • 1,480 Points 1k badge 2x thumb
Hi Zach,

When i did add row on salesforce standard object (Contact) then row is added with specified value in fields in skuid table.

But when i used external object then its only adding row with blank value in column.

Here is xml of skuid page :

<skuidpage unsavedchangeswarning="yes" showsidebar="true" showheader="true">   <models>
      <model id="Contact" limit="20" query="false" createrowifnonefound="false" sobject="Contact" doclone="" type="">
         <fields>
            <field id="FirstName"/>
            <field id="LastName"/>
         </fields>
         <conditions/>
         <actions/>
      </model>
      <model id="Result" limit="20" query="false" createrowifnonefound="false" sobject="Events__x" doclone="" type="">
         <fields>
            <field id="StaffUserId__c"/>
            <field id="LeadStaffEmail__c"/>
         </fields>
         <conditions/>
         <actions/>
      </model>
   </models>
   <components>
      <pagetitle model="Contact">
         <subtitle>
            <template>{{Model.label}}</template>
         </subtitle>
         <actions>
            <action type="multi" label="Add Row">
               <actions>
                  <action type="custom" snippet="addRowInModelWithDefaultValue"/>
               </actions>
               <hotkeys/>
               <renderconditions logictype="and"/>
            </action>
         </actions>
      </pagetitle>
      <skootable showconditions="true" showsavecancel="true" searchmethod="server" searchbox="true" showexportbuttons="false" pagesize="10" createrecords="true" model="Result" buttonposition="" mode="read">
         <fields>
            <field id="StaffUserId__c"/>
            <field id="LeadStaffEmail__c"/>
         </fields>
         <rowactions>
            <action type="edit"/>
            <action type="delete"/>
         </rowactions>
         <massactions usefirstitemasdefault="true">
            <action type="massupdate"/>
            <action type="massdelete"/>
         </massactions>
         <views>
            <view type="standard"/>
         </views>
      </skootable>
      <skootable showconditions="true" showsavecancel="true" searchmethod="server" searchbox="true" showexportbuttons="false" pagesize="10" createrecords="true" model="Contact" buttonposition="" mode="read">
         <fields>
            <field id="FirstName"/>
            <field id="LastName"/>
         </fields>
         <rowactions>
            <action type="edit"/>
            <action type="delete"/>
         </rowactions>
         <massactions usefirstitemasdefault="true">
            <action type="massupdate"/>
            <action type="massdelete"/>
         </massactions>
         <views>
            <view type="standard"/>
         </views>
      </skootable>
   </components>
   <resources>
      <labels/>
      <javascript>
         <jsitem location="inlinesnippet" name="addRowInModelWithDefaultValue" cachelocation="false">var params = arguments[0],
$ = skuid.$;

var Contact = skuid.model.getModel('Contact');
Contact.emptyData();

Contact.createRow({
                        additionalConditions: [
                            { field: 'FirstName', value:'Rajendra Rathore'},
                            
                            { field: 'LastName', value: 'lastname'}
                        ], doAppend:true 
                        
                        });
                        
                        var ResultModel = skuid.model.getModel('Result');
ResultModel.emptyData();

                        ResultModel.createRow({
                        additionalConditions: [
                            { field: 'StaffUserId__c', value:'Rajendra'},
                            
                            { field: 'LeadStaffEmail__c', value: 'test@gmail.com'}
                        ], doAppend:true 
                        
                        });</jsitem>
      </javascript>
      <css/>
   </resources>
</skuidpage>
Photo of Rajendra Rathore

Rajendra Rathore

  • 1,480 Points 1k badge 2x thumb
Hi Zach,

So in case of external object is not possible to add row with default value in columns in a skuid table?

Thanks
Photo of Zach McElrath

Zach McElrath, Employee

  • 49,056 Points 20k badge 2x thumb
Rajendra,

In the case of External Objects it will not be possible to create / update / delete any way at all, regardless of how you try to do it --- Salesforce's External Objects feature is currently universally Read-Only. Skuid is detecting that you are trying to update field values on an external object row, and those fields' metadata are returning read-only, so Skuid is not applying your updates. 

You will not be able to use Skuid to write values to external data objects at this point because Salesforce does not support that.
Photo of Rajendra Rathore

Rajendra Rathore

  • 1,480 Points 1k badge 2x thumb
Okey Zach! Thanks 
Photo of Ryan Paddy

Ryan Paddy

  • 306 Points 250 badge 2x thumb
Thanks. Obvious in hindsight!
Photo of Jack Sanford

Jack Sanford, Champion

  • 8,322 Points 5k badge 2x thumb
This isn't working for me, somehow the save isn't waiting to be completed. I'm trying to do this in a $.each function so maybe that's why? It should be creating three rows in the DREFs1 model, and it does, but for my alert I just get 4, then 6, then 6 instead of a SF ID.

Here's the code
var params = arguments[0],
	$ = skuid.$,
	models = skuid.model.map();

// grab ids of all selected rows



// model to add seleted rows from
var conditionTemplates = skuid.model.getModel('ConditionTemplates');
var rows = conditionTemplates.getRows();


// model to add to
var conditions = skuid.model.getModel('Conditions');
var drefs = skuid.model.getModel('DREFs1');

//other models

var oppModel = skuid.model.getModel('Opportunity');
var oppRow = oppModel.getFirstRow();
var oppId = oppModel.getFieldValue(oppRow,'Id');



// for each selected row, add a new row
$.each(rows, function(){
	
	
	// get selected row data
	var templateRow = this;
	
	// set variables for selected row field(s)
	var templateId = conditionTemplates.getFieldValue(templateRow, 'Id');
	var templateName = conditionTemplates.getFieldValue(templateRow, 'Name');
	var templateType = conditionTemplates.getFieldValue(templateRow, 'Type__c');
	var templateDescription = conditionTemplates.getFieldValue(templateRow, 'Description__c');
	var templateHelp = conditionTemplates.getFieldValue(templateRow, 'Help__c');
	var drefTemplate = conditionTemplates.getFieldValue(templateRow, 'DocumentReferenceTemplate__r.Id');
	var drefTitle = conditionTemplates.getFieldValue(templateRow, 'DocumentReferenceTemplate__r.Title__c');
	var drefParty = conditionTemplates.getFieldValue(templateRow, 'DocumentReferenceTemplate__r.ProvidingParty__c');
	
	
	drefs.createRow({
		additionalConditions: [
			{field: 'DocumentReferenceTemplate__c', value: drefTemplate, operator: '='},
			{field: 'DocumentTitle__c', value: drefTitle, operator: '='},
			{field: 'Opportunity__c', value: oppId, operator: '='},
			{field: 'ProvidingParty__c', value: drefParty, operator: '='}
		]
	});
	
	
	drefs.save({callback: function(result){
	if (result.totalsuccess) {
		d = drefs.getFirstRow();
		alert(d.Id);
		var drefId = drefs.getFieldValue(d, 'Id');
		var conditionRow = conditions.createRow({
		additionalConditions: [
			{field: 'ConditionTemplate__c', value: templateId, operator: '='},
			{field: 'Name__c', value: templateName, operator: '='},
			{field: 'Type__c', value: templateType, operator: '='},
			{field: 'Description__c', value: templateDescription, operator: '='},
			{field: 'Help__c', value: templateHelp, operator: '='},
			{field: 'Opportunity__c', value: oppId, operator: '='},
			{field: 'DocumentReference__c', value: drefId, operator: '='}
			
		]
	});
	} else {
		console.log(result.insertResults[0]);
		
	}
}});
	
	
	 
	
	
	

});

// save updated model
conditions.save({callback: function(result){
	if (result.totalsuccess) {
		//console.log(quotelines);
	} else {
		console.log(result.insertResults);
		console.log(result.updateResults);
		console.log(result.deleteResults);
	}
}});
(Edited)
Photo of Zach McElrath

Zach McElrath, Employee

  • 49,056 Points 20k badge 2x thumb
Jack, I recommend NOT doing a .save() call within a loop (i.e. within your $.each) --- I recommend refactoring your code to do this:

1. create all of your drefs, e.g. one createRow() for each dref you want to create
2. save all the new drefs you created --- using just ONE call to drefs.save()
3. in the drefs.save() callback, iterate over result.insertResults and create condition rows in your conditions Model
4. Do ONE call to conditions.save()

Anytime you're doing a .save() within an $.each(), you're going to problems. Not only will your code be very very slow (because you're doing a separate save call, which goes to the server, for each row you're saving!), it's going to be hard to debug and understand.
Photo of Jack Sanford

Jack Sanford, Champion

  • 8,322 Points 5k badge 2x thumb
Thanks!
Photo of Jack Sanford

Jack Sanford, Champion

  • 8,322 Points 5k badge 2x thumb
So, I wasn't sure how to get at each of the Condition Templates again in the drefs.save results, since the Condition Templates aren't related to the drefs after they are created. 

My workaround was within the $.each to create all the drefs rows, then create all the conditions rows, then after creating all the rows and outside the $.each, save the drefs, then save the conditions within the success results of the drefs.

This matches the right drefs to the new conditions and doesn't make any on-screen bold red errors, but it does throw a silent error and stops the saving. The result is I've got my table of Conditions with the right info but unsaved changes.

What I could do is manually hit Save on the table - instead in the action framework, I use an On-Error action with the Snippet that saves the Conditions model, and it all comes out perfect.


So the final code comes out like below, finished off with the action framework.

var params = arguments[0],
	$ = skuid.$,
	models = skuid.model.map();

// grab ids of all selected rows



// model to add seleted rows from
var conditionTemplates = skuid.model.getModel('ConditionTemplates');
var rows = conditionTemplates.getRows();


// model to add to
var conditions = skuid.model.getModel('Conditions');
var drefs = skuid.model.getModel('DREFs1');

//other models

var oppModel = skuid.model.getModel('Opportunity');
var oppRow = oppModel.getFirstRow();
var oppId = oppModel.getFieldValue(oppRow,'Id');
var oppTemplateGroup = oppModel.getFieldValue(oppRow,'Template_Group__c');



// for each selected row, add a new row
$.each(rows, function(){
	
	
	// get selected row data
	var templateRow = this;
	
	// set variables for selected row field(s)
	var templateId = conditionTemplates.getFieldValue(templateRow, 'Id');
	var templateName = conditionTemplates.getFieldValue(templateRow, 'Name');
	var templateType = conditionTemplates.getFieldValue(templateRow, 'Type__c');
	var templateDescription = conditionTemplates.getFieldValue(templateRow, 'Description__c');
	var templateHelp = conditionTemplates.getFieldValue(templateRow, 'Help__c');
	var drefTemplateId = conditionTemplates.getFieldValue(templateRow, 'DocumentReferenceTemplate__r.Id');
	var drefTitle = conditionTemplates.getFieldValue(templateRow, 'DocumentReferenceTemplate__r.Title__c');
	var drefParty = conditionTemplates.getFieldValue(templateRow, 'DocumentReferenceTemplate__r.ProvidingParty__c');
	var drefMan = conditionTemplates.getFieldValue(templateRow, 'DocumentReferenceTemplate__r.Mandatory__c');
	
	
	var drefRow = drefs.createRow({
		additionalConditions: [
			{field: 'DocumentReferenceTemplate__c', value: drefTemplateId, operator: '='},
			{field: 'DocumentTitle__c', value: drefTitle, operator: '='},
			{field: 'Opportunity__c', value: oppId, operator: '='},
			{field: 'ProvidingParty__c', value: drefParty, operator: '='},
			{field: 'Mandatory__c', value: drefMan, operator: '='},

			{field: 'TemplateGroup__c', value: oppTemplateGroup, operator: '='}
		]
	});
	var conditionRow = conditions.createRow({
		additionalConditions: [
			{field: 'ConditionTemplate__c', value: templateId, operator: '='},
			{field: 'Name__c', value: templateName, operator: '='},
			{field: 'Type__c', value: templateType, operator: '='},
			{field: 'Description__c', value: templateDescription, operator: '='},
			{field: 'Help__c', value: templateHelp, operator: '='},
			{field: 'Opportunity__c', value: oppId, operator: '='},
			{field: 'DocumentReference__c', value: drefRow.Id, operator: '='}
			
		]
	});
	
	
	
	
	 
	
	
	

});


drefs.save({callback: function(result){
	if (result.totalsuccess) {
		
	console.log('Success DREFs');
	conditions.save({callback: function(result){
	if (result.totalsuccess) {
	console.log('Success Conditions 1');
	} else {
		console.log(result.insertResults);
		console.log(result.updateResults);
		console.log(result.deleteResults);
	}
}});	
	} else {
		console.log(result.insertResults);
		
	}
}});