简体   繁体   中英

Retrieve object id from newly created salesforce object

I'm trying to create a parent object and it's children with the Salesforce SDK. From what I can tell there is no way to do this in one operation so I need to first create the parent object and then create each child object one by one.

My problem is that I'm unsure how to get the id of the newly created parent object which I need to create it's children. I know that the response returned in the SFRestDelegate method request:didLoadResponse: contains the id but I'm not sure how to capture that in my create function.

let api = SFRestAPI.sharedInstance()

var parent = [NSObject : AnyObject]()
parent["Field1__c"] = "Test"
parent["Field2__c"] = "Test"

let createRequest = api.requestForCreateWithObjectType("Parent_Object__c", fields: parent)
api.send(createRequest, delegate: self)

// Need wait for response before continuing...???
// id = ??

for var i = 0; i < 3; ++i {
    let child = ["Test_Object__c": id, "Name": "Child1\(i)"]
    let createRequest = api.requestForCreateWithObjectType("Parent_Object__c", fields: child)
    api.send(createRequest, delegate: self)
}

I'm thinking there must be a more efficient way to do this but I haven't found it in the docs if there is.

Any help would be appreciated!

You have set the delegate as self so all you now need to do is to actually provide the methods that this implies (ie the handlers for the request). Inside this object implement these four methods:

func request(request: SFRestRequest?, didLoadResponse jsonResponse: AnyObject) {

    var records = jsonResponse.objectForKey("records") as! NSArray
    //do stuff with your records
    //call createChildRecords method here. You can extract the id from the records object above.
}

func request(request: SFRestRequest?, didFailLoadWithError error:NSError) {
    println("In Error: \(error)")
}

func requestDidCancelLoad(request: SFRestRequest) {
    println("In requestDidCancelLoad \(request)")
}


func requestDidTimeout(request: SFRestRequest) {
    println("In requestDidTimeout \(request)")
}

The for loop that you have following the request should be in another method that you can call from the successful load method that you implemented as part of the delegate protocol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM