You are here

public function SmsBlastForm::submitForm in SMS Framework 8

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

File

modules/sms_blast/src/SmsBlastForm.php, line 84

Class

SmsBlastForm
Defines a form for sending mass messages.

Namespace

Drupal\sms_blast

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $sms_message = new SmsMessage();
  $sms_message
    ->setMessage($form_state
    ->getValue('message'));
  $ids = $this->phoneNumberVerificationStorage
    ->getQuery()
    ->condition('status', 1)
    ->condition('entity__target_type', 'user')
    ->execute();
  $success = 0;
  $failure = 0;
  $entity_ids = [];

  /** @var \Drupal\sms\Entity\PhoneNumberVerificationInterface $verification */
  foreach ($this->phoneNumberVerificationStorage
    ->loadMultiple($ids) as $verification) {

    // Ensure entity exists and one message is sent to each entity.
    if (($entity = $verification
      ->getEntity()) && !in_array($entity
      ->id(), $entity_ids)) {
      $entity_ids[] = $entity
        ->id();
      try {
        $this->phoneNumberProvider
          ->sendMessage($entity, $sms_message);
        $success++;
      } catch (\Exception $e) {
        $failure++;
      }
    }
  }
  if ($success > 0) {
    drupal_set_message($this
      ->formatPlural($success, 'Message sent to @count user.', 'Message sent to @count users.'));
  }
  if ($failure > 0) {
    drupal_set_message($this
      ->formatPlural($failure, 'Message could not be sent to @count user.', 'Message could not be sent to @count users.'), 'error');
  }
}