You are here

function contact_emails_update_8006 in Contact Emails 8

Add 'message' field to 'contact_email' entities and remove 'body'.

** IMPORTANT ** If you extended or used the body field with your own bespoke module, you must update your code appropriately to use "message" instead of "body". If you have been using this module as is, this update will apply safely without issue.

File

./contact_emails.install, line 241
Contact emails database table.

Code

function contact_emails_update_8006(&$sandbox) {
  $updateManager = \Drupal::entityDefinitionUpdateManager();
  $existing_message_storage_definition = $updateManager
    ->getFieldStorageDefinition('message', 'contact_email');
  $existing_body_storage_definition = $updateManager
    ->getFieldStorageDefinition('body', 'contact_email');

  // Initialize the batch update.
  if (!isset($sandbox['progress'])) {

    // Ensure we don't yet have a contact email message field.
    if (!$existing_message_storage_definition) {

      // Install the new field storage definition for message.
      $storage_definition = BaseFieldDefinition::create('text_long')
        ->setLabel(t('Message'))
        ->setDescription(t('The email message body.'))
        ->setDefaultValue('')
        ->setTranslatable(TRUE)
        ->setSettings([
        'max_length' => 9999,
        'text_processing' => 0,
      ])
        ->setDisplayOptions('form', [
        'type' => 'text_textarea',
        'weight' => -5,
        'settings' => [
          'rows' => 4,
        ],
      ]);
      $updateManager
        ->installFieldStorageDefinition('message', 'contact_email', 'contact_email', $storage_definition);
    }

    // This must be the first run. Initialize the sandbox.
    $sandbox['progress'] = 0;
    $sandbox['current_id'] = 0;

    // Count the contact emails.
    $sandbox['max'] = \Drupal::entityQuery('contact_email')
      ->count()
      ->execute();
  }
  if (!empty($sandbox['max'])) {

    // Update in chunks of 10.
    $contact_email_ids = \Drupal::entityQuery('contact_email')
      ->condition('email_id', $sandbox['current_id'], '>')
      ->range(0, 10)
      ->execute();
    $connection = \Drupal::database();
    $contact_emails = \Drupal::entityTypeManager()
      ->getStorage('contact_email')
      ->loadMultiple($contact_email_ids);
    foreach ($contact_emails as $contact_email) {
      $message = [];

      // Move the body into the message. The body no longer exists in the
      // definition so we must get it with a query.
      if ($connection
        ->schema()
        ->fieldExists('contact_email_field_data', 'body')) {
        $fields = $connection
          ->select('contact_email_field_data', 'c')
          ->fields('c', [
          'body',
        ])
          ->condition('c.email_id', $contact_email
          ->id(), '=')
          ->execute()
          ->fetchObject();
        if ($fields && !empty($fields->body)) {

          // The format and value were previously stored in a serialized array
          // in the single column.
          $unserialised_body = unserialize($fields->body, [
            'allowed_classes' => FALSE,
          ]);
          if (isset($unserialised_body['format'], $unserialised_body['value'])) {
            $message = [
              'value' => $unserialised_body['value'],
              'format' => $unserialised_body['format'],
            ];
          }
        }
      }

      // In case the user ran entity-updates prior to updb.
      if (!isset($message['value']) && $connection
        ->schema()
        ->fieldExists('contact_email_field_data', 'message__value')) {
        $fields = $connection
          ->select('contact_email_field_data', 'c')
          ->fields('c', [
          'message__value',
          'message__format',
        ])
          ->condition('c.email_id', $contact_email
          ->id(), '=')
          ->execute()
          ->fetchObject();
        if ($fields && !empty($fields->message__value)) {
          $unserialised_body = unserialize($fields->message__value, [
            'allowed_classes' => FALSE,
          ]);
          if (isset($unserialised_body['format']) && isset($unserialised_body['value'])) {
            $message = [
              'value' => $unserialised_body['value'],
              'format' => $unserialised_body['format'],
            ];
          }
        }
      }

      // Save the new message format to the contact email.
      if (isset($message['value'])) {
        $contact_email
          ->set('message', $message);
        $contact_email
          ->save();
      }
      $sandbox['progress']++;
      $sandbox['current_id'] = $contact_email
        ->id();
    }
    $sandbox['#finished'] = empty($sandbox['max']) ? 1 : $sandbox['progress'] / $sandbox['max'];
  }
  else {
    $sandbox['#finished'] = 1;
  }
  if ($existing_body_storage_definition && $sandbox['#finished'] >= 1) {
    $updateManager
      ->uninstallFieldStorageDefinition($existing_body_storage_definition);
  }
  return t('All emails have have the serialised body field converted to the message field for compatibility with rest API. ** If you extended or used the body field with your own bespoke module, you must update your code appropriately to use "message" instead of "body". If you have been using this module as is, this update will apply safely without issue. **');
}