You are here

public function RedhenContact::upsert in RedHen CRM 7

Saves a new contact unless a matching contact is found to update.

Updates are performed if a single contact is found matching the email address and bundle of the one being saved.


modules/redhen_contact/lib/, line 258
Redhen Contact entity classses.


The class used for contact entities.


public function upsert() {
  if (isset($this->is_new) && $this->is_new && !isset($this->created)) {
    $this->updated = REQUEST_TIME;
    $contact_wrapper = entity_metadata_wrapper('redhen_contact', $this);
    $query = new EntityFieldQuery();
      ->entityCondition('entity_type', 'redhen_contact')
      ->entityCondition('bundle', $contact_wrapper
      ->fieldCondition('redhen_contact_email', 'value', $contact_wrapper->email
      ->value(), '=');
    $result = $query
    if (isset($result['redhen_contact']) && count($result['redhen_contact']) === 1) {
      list($contact_id) = array_keys($result['redhen_contact']);
      $existing_wrapper = entity_metadata_wrapper('redhen_contact', $contact_id);
      foreach ($existing_wrapper
        ->getPropertyInfo() as $property => $info) {
        if (isset($info['setter callback']) && $existing_wrapper->{$property}
          ->value() !== NULL && $contact_wrapper->{$property}
          ->value() === NULL) {

          // @todo consider a flag to avoid overriding with new values.

      // We aren't creating a new contact, we are updating an old one, so:
      $this->contact_id = $existing_wrapper
      $this->is_new_revision = TRUE;
      $this->default_revision = TRUE;
  return $this