Undefined array key "id" in Drupal\civicrm_entity\CiviEntityStorage->doSave()

Created on 25 July 2024, 5 months ago
Updated 4 September 2024, 4 months ago

Problem/Motivation

During the programatically create of a contact and assigning it to a tag, an error related to the `civicrm_entity_tag` entity occurs because the code expects the `$result` variable to have an 'id' key, which is missing in this case.
Warning: Undefined array key "id" in Drupal\civicrm_entity\CiviEntityStorage->doSave() (line 138 of /var/www/html/www/modules/contrib/civicrm_entity/src/CiviEntityStorage.php)

Steps to reproduce

1. Create a contact or find and existing using the `entity_type.manager`.
2. Create or find an existing tag using the `entity_type.manager`.
3. Create a tag assignment for the contact using the `entity_type.manager`.

    $entityTag = $this->entityTypeManager->getStorage('civicrm_entity_tag')->create([
      'entity_table' => 'civicrm_contact',
      'entity_id' => $contact_id,
      'tag_id' => $this->getTagId(),
    ]);
    $entityTag->enforceIsNew()->save();

4. A PHP error occurs.

Proposed resolution

To fix this, simply add a check to the line causing the error.
Before:

    if ($entity->isNew()) {
      $entity->{$this->idKey} = (string) $result['id'];
    }

After:

    if ($entity->isNew()) {
      $entity->{$this->idKey} = (string) ($result['id'] ?? '');
    }
🐛 Bug report
Status

Closed: outdated

Version

4.0

Component

Code

Created by

🇵🇱Poland michal_liszka

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024