You are here

public function RestClient::objectUpsert in Salesforce Suite 8.4

Same name and namespace in other branches
  1. 8.3 src/Rest/RestClient.php \Drupal\salesforce\Rest\RestClient::objectUpsert()
  2. 5.0.x src/Rest/RestClient.php \Drupal\salesforce\Rest\RestClient::objectUpsert()

Create new records or update existing records.

The new records or updated records are based on the value of the specified field. If the value is not unique, REST API returns a 300 response with the list of matching records and throws an Exception.

Parameters

string $name: Object type name, E.g., Contact, Account.

string $key: The field to check if this record should be created or updated.

string $value: The value for this record of the field specified for $key.

array $params: Values of the fields to set for the object.

Return value

\Drupal\salesforce\SFID The new object's SFID, if created. NULL if updated. This is not ideal, but this is how Salesforce's API works. Go upvote this idea to fix it:

Overrides RestClientInterface::objectUpsert

1 method overrides RestClient::objectUpsert()
TestRestClient::objectUpsert in src/Tests/TestRestClient.php
Create new records or update existing records.

File

src/Rest/RestClient.php, line 505

Class

RestClient
Objects, properties, and methods to communicate with the Salesforce REST API.

Namespace

Drupal\salesforce\Rest

Code

public function objectUpsert($name, $key, $value, array $params) {

  // If key is set, remove from $params to avoid UPSERT errors.
  if (isset($params[$key])) {
    unset($params[$key]);
  }
  $response = $this
    ->apiCall("sobjects/{$name}/{$key}/{$value}", $params, 'PATCH', TRUE);

  // On update, upsert method returns an empty body. Retreive object id, so
  // that we can return a consistent response.
  if ($response
    ->getStatusCode() == 204) {

    // We need a way to allow callers to distinguish updates and inserts. To
    // that end, cache the original response and reset it after fetching the
    // ID.
    $this->original_response = $response;
    $sf_object = $this
      ->objectReadbyExternalId($name, $key, $value);
    return $sf_object
      ->id();
  }
  $data = $response->data;
  return new SFID($data['id']);
}