You are here

class WebformEmailReplyForm in Webform Email Reply 8

Hierarchy

Expanded class hierarchy of WebformEmailReplyForm

1 string reference to 'WebformEmailReplyForm'
webform_email_reply.routing.yml in ./webform_email_reply.routing.yml
webform_email_reply.routing.yml

File

src/Form/WebformEmailReplyForm.php, line 21
Contains \Drupal\webform_email_reply\Form\WebformEmailReplyForm.

Namespace

Drupal\webform_email_reply\Form
View source
class WebformEmailReplyForm extends FormBase {

  /**
   * A webform submission.
   *
   * @var \Drupal\webform\WebformSubmissionInterface
   */
  protected $webformSubmission;

  /**
   * The source entity.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $entity;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'webform_email_reply_form';
  }

  /**
   * Webform request handler.
   *
   * @var \Drupal\webform\WebformRequestInterface
   */
  protected $requestHandler;

  /**
   * Current user account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $current_user;

  /**
   * Constructs a WebformResultsResendForm object.
   *
   * @param \Drupal\webform\WebformRequestInterface $request_handler
   *   The webform request handler.
   */
  public function __construct(WebformRequestInterface $request_handler, AccountInterface $current_user) {
    $this->requestHandler = $request_handler;
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('webform.request'), $container
      ->get('current_user'));
  }

  /**
   * Check that webform submission resend access check.
   *
   * @param \Drupal\webform\WebformSubmissionInterface $webform_submission
   *   A webform submission.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public static function checkReplyAccess(WebformSubmissionInterface $webform_submission, AccountInterface $account) {
    if ($webform_submission
      ->getWebform()
      ->hasMessageHandler()) {
      if ($account
        ->hasPermission('send email replies to all webforms') || $account
        ->hasPermission('send email replies to own webforms')) {
        return AccessResult::allowed();
      }
    }
    return AccessResult::forbidden();
  }
  public function buildForm(array $form, FormStateInterface $form_state, $node = NULL, WebformSubmissionInterface $webform_submission = NULL) {
    $this->webformSubmission = $webform_submission;

    // Prepopulate values.
    $user = $this->currentUser;
    $default_from_email = \Drupal::config('system.site')
      ->get('mail');
    $title = $webform_submission
      ->getWebform()
      ->label();
    $webform_id = $webform_submission
      ->getWebform()
      ->id();
    $sid = $webform_submission
      ->id();

    // Only display link if there are replies.
    $replies = webform_email_reply_get_replies($webform_id, $sid);
    $replies_count = count($replies);
    if ($replies_count) {
      $form['previous_replies'] = [
        '#type' => 'link',
        '#title' => \Drupal::translation()
          ->formatPlural($replies_count, '1 previous reply', '@count previous replies'),
        '#url' => Url::fromRoute('webform_email_reply.previous', [
          'webform' => $webform_id,
          'webform_submission' => $sid,
        ]),
      ];
    }
    $form['#tree'] = TRUE;
    $form['details']['webform_id'] = [
      '#type' => 'value',
      '#value' => $webform_id,
    ];
    $form['details']['sid'] = [
      '#type' => 'value',
      '#value' => $sid,
    ];
    $form['details']['from_address'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('From'),
      '#default_value' => $default_from_email,
      '#description' => $this
        ->t('The email address to send from.'),
      '#required' => TRUE,
    ];
    $form['details']['email'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Email'),
      '#description' => $this
        ->t('The email address(es) to send to. Multiple emails should be separated by a comma, with no spaces.'),
      '#required' => TRUE,
    ];
    $form['details']['subject'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Subject'),
      '#default_value' => $this
        ->t('RE: @title', [
        '@title' => strip_tags($title),
      ]),
      '#required' => TRUE,
    ];
    $form['details']['message'] = [
      '#type' => 'webform_html_editor',
      '#title' => $this
        ->t('Message'),
      '#required' => TRUE,
    ];
    $form['details']['attachement'] = [
      '#type' => 'managed_file',
      '#title' => $this
        ->t("Attachment"),
      '#upload_location' => 'public://webform_email_reply/',
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Send'),
    ];

    // Add submission navigation.
    $source_entity = $this->requestHandler
      ->getCurrentSourceEntity('webform_submission');
    $form['navigation'] = [
      '#type' => 'webform_submission_navigation',
      '#webform_submission' => $webform_submission,
      '#weight' => -20,
    ];
    $form['information'] = [
      '#type' => 'webform_submission_information',
      '#webform_submission' => $webform_submission,
      '#source_entity' => $source_entity,
      '#weight' => -19,
    ];
    $form['#attached']['library'][] = 'webform/webform.admin';
    $form['#attached']['library'][] = 'webform/webform.element.html_editor';
    return $form;
  }
  public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $from_email = $form_state
      ->getValue([
      'details',
      'from_address',
    ]);
    if (!valid_email_address($from_email)) {
      $form_state
        ->setErrorByName('details][from_address', $this
        ->t('The from email address, @email, is not valid. Please enter a valid email address.', [
        '@email' => $from_email,
      ]));
    }
    $valid_email = explode(',', $form_state
      ->getValue([
      'details',
      'email',
    ]));
    foreach ($valid_email as $email) {
      if (!valid_email_address($email)) {
        $form_state
          ->setErrorByName('details][email', $this
          ->t('The email address, @email, is not valid. Please enter a valid email address.', [
          '@email' => $email,
        ]));
      }
    }
  }
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $webform_id = $form_state
      ->getValue([
      'details',
      'webform_id',
    ]);
    $sid = $form_state
      ->getValue([
      'details',
      'sid',
    ]);
    $emails = explode(',', $form_state
      ->getValue([
      'details',
      'email',
    ]));
    $body = $form_state
      ->getValue([
      'details',
      'message',
    ]);
    $subject = $form_state
      ->getValue([
      'details',
      'subject',
    ]);
    $file = $form_state
      ->getValue([
      'details',
      'attachement',
    ]);
    $params = [
      'body' => $body,
      'subject' => $subject,
    ];
    $from_address = $form_state
      ->getValue([
      'details',
      'from_address',
    ]);
    $params['from'] = $from_address;

    // Data for saving in schema.
    $data = $form_state
      ->getValue([
      'details',
    ]);

    // Saving files permanently.
    if (isset($file[0])) {
      $file = File::load($file[0]);
      $file
        ->setPermanent();
      $file
        ->save();
      $data['fid'] = $file
        ->id();
      $params['attachments'][] = [
        'filecontent' => file_get_contents($file
          ->getFileUri()),
        'filename' => $file
          ->getFilename(),
        'filemime' => $file
          ->getMimeType(),
        'filepath' => \Drupal::service('file_system')
          ->realpath($file
          ->getFileUri()),
        '_uri' => file_create_url($file
          ->getFileUri()),
      ];
      $params['headers'] = [
        'MIME-Version' => '1.0',
        'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
        'Content-Transfer-Encoding' => '8Bit',
        'X-Mailer' => 'Drupal',
      ];
    }

    // Send each emails individually.
    foreach ($emails as $email) {
      $mail_sent = \Drupal::service('plugin.manager.mail')
        ->mail('webform_email_reply', 'email', $email, $this->currentUser
        ->getPreferredLangcode(), $params, NULL, TRUE);
      if ($mail_sent) {
        \Drupal::messenger()
          ->addMessage($this
          ->t('Reply email sent to @email from @from_address.', [
          '@email' => $email,
          '@from_address' => $from_address,
        ]));

        // Insert the values into the database.
        webform_email_reply_insert($data);
      }
      else {
        \Drupal::messenger()
          ->addError($this
          ->t('There was an error sending the email to @email, please contact the site admin.', [
          '@email' => $email,
        ]));
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.
WebformEmailReplyForm::$current_user protected property Current user account.
WebformEmailReplyForm::$entity protected property The source entity.
WebformEmailReplyForm::$requestHandler protected property Webform request handler.
WebformEmailReplyForm::$webformSubmission protected property A webform submission.
WebformEmailReplyForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
WebformEmailReplyForm::checkReplyAccess public static function Check that webform submission resend access check.
WebformEmailReplyForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
WebformEmailReplyForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
WebformEmailReplyForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
WebformEmailReplyForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
WebformEmailReplyForm::__construct public function Constructs a WebformResultsResendForm object.