SmsBlastForm.php in SMS Framework 8
File
modules/sms_blast/src/SmsBlastForm.php
View source
<?php
namespace Drupal\sms_blast;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\sms\Provider\PhoneNumberProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\sms\Message\SmsMessage;
class SmsBlastForm extends FormBase {
protected $phoneNumberVerificationStorage;
protected $phoneNumberProvider;
public function __construct(EntityTypeManagerInterface $entity_type_manager, PhoneNumberProviderInterface $phone_number_provider) {
$this->phoneNumberVerificationStorage = $entity_type_manager
->getStorage('sms_phone_number_verification');
$this->phoneNumberProvider = $phone_number_provider;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('entity_type.manager'), $container
->get('sms.phone_number'));
}
public function getFormId() {
return 'sms_blast_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['message'] = [
'#type' => 'textarea',
'#title' => $this
->t('Message'),
'#cols' => 60,
'#rows' => 5,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Send'),
];
return $form;
}
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 = [];
foreach ($this->phoneNumberVerificationStorage
->loadMultiple($ids) as $verification) {
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');
}
}
}