You are here

function contact_emails_update_8001 in Contact Emails 8

Modify how the recipient type is stored.

File

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

Code

function contact_emails_update_8001(&$sandbox) {
  $connection = \Drupal::database();
  $schema = $connection
    ->schema();
  if ($connection
    ->schema()
    ->tableExists('contact_message_email_settings')) {

    // Add the new recipient type field.
    $recipient_type = [
      'type' => 'varchar',
      'length' => 20,
      'not null' => TRUE,
      'default' => 'manual',
      'description' => 'How to determine the submitter of the form.',
    ];
    if (!$schema
      ->fieldExists('contact_message_email_settings', 'recipient_type')) {
      $schema
        ->addField('contact_message_email_settings', 'recipient_type', $recipient_type);
    }

    // Add the new recipient field for when the recipient type is field.
    $recipient_field = [
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'default' => '',
      'description' => 'The field to send to if recipient type is field.',
    ];
    if (!$schema
      ->fieldExists('contact_message_email_settings', 'recipient_field')) {
      $schema
        ->addField('contact_message_email_settings', 'recipient_field', $recipient_field);
    }

    // Get the form ids that are using the form submitter as the recipient.
    $query = $connection
      ->select('contact_message_email_settings', 'c');
    $query
      ->addField('c', 'id');
    $query
      ->condition('c.recipient_is_submitter', '1');
    $ids = $query
      ->execute()
      ->fetchCol();

    // Update the database to store that in the recipient type field instead.
    if ($ids) {
      $query = $connection
        ->update('contact_message_email_settings');
      $query
        ->fields([
        'recipient_type' => 'submitter',
      ]);
      $query
        ->condition('id', $ids, 'IN');
      $query
        ->execute();
    }

    // Remove the recipient_is_submitter field.
    if ($schema
      ->fieldExists('contact_message_email_settings', 'recipient_is_submitter')) {
      $schema
        ->dropField('contact_message_email_settings', 'recipient_is_submitter');
    }
  }
}