1

I'm using this code to create an entry in a custom object which works. I'd like to replace the create with upsert to handle updating existing entries in the custom object when the entry ID is available before posting to the API, or create a new record if no ID is available.

try {

  $sObject = new stdclass();
  $sObject->Name = 'This is the name';
  $sObject->Contact__c = 'XXXXXXXXXX';
  $sObject->Post__c = 'the post body';
  $sObject->URL__c = 'http://www.example.com';

  $createResponse = $mySforceConnection->create(array($sObject), 'CustomObjName_Entries__c');

  $ids = array();
  foreach ($createResponse as $createResult) {
    print_r($createResult);
    array_push($ids, $createResult->id);
  }

} catch (Exception $e) {
  echo $mySforceConnection->getLastRequest();
  echo $e->faultstring;
}

So what i'm trying to do is something like this, i'll stored existing ID's locally and place them into a variable $sfid the ID field is checked in upsert if it exists it should update the existing record right?

$sfid = 'XXXXXXXXXX'; // Existing custom object entry ID

try {

  $sObject = new stdclass();
      $sObject->ID = $sfid;
  $sObject->Name = 'This is the name';
  $sObject->Contact__c = 'XXXXXXXXXX';
  $sObject->Post__c = 'the post body';
  $sObject->URL__c = 'http://www.example.com';

  $createResponse = $mySforceConnection->upsert("ID",array($sObject), 'CustomObjName_Entries__c');

  $ids = array();
  foreach ($createResponse as $createResult) {
    print_r($createResult);
    array_push($ids, $createResult->id);
  }

} catch (Exception $e) {
  echo $mySforceConnection->getLastRequest();
  echo $e->faultstring;
}

In the new code I am setting the sObject ID from my sfid variable.

Looking at the example at http://wiki.developerforce.com/page/PHP_Toolkit_20.0_Upsert_Sample_(Partner)

Is the "Email" field on line 35 used to check if that email / record exists then update the first and last name for that record?

My code does seem to work after testing but is this a proper way of using upsert? Can the code be improved in any way?

5

Upsert has two modes of operation. The first is to create a record if no ID is specified, or update the record if an ID is specified, and the second is to take an "external ID" and create a record if no matching external ID is found, or update the record if exactly one external ID is found. In this case, you're using the former mode of operation, and that's exactly the use case that upsert was designed to handle as a matter of simplifying external and internal business logic.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.