You are here

class ContactEmailForm in Contact Emails 8

Defines the tax service add/edit form.

Hierarchy

Expanded class hierarchy of ContactEmailForm

File

src/Form/ContactEmailForm.php, line 17

Namespace

Drupal\contact_emails\Form
View source
class ContactEmailForm extends ContentEntityForm {

  /**
   * Drupal\contact_emails\ContactEmails definition.
   *
   * @var \Drupal\contact_emails\ContactEmails
   */
  protected $contactEmails;

  /**
   * Constructs a ContentEntityForm object.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   * @param \Drupal\contact_emails\ContactEmails $contact_emails
   *   The contact emails service.
   */
  public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info, TimeInterface $time, ContactEmails $contact_emails) {
    $this->entityRepository = $entity_repository;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    $this->time = $time;
    $this->contactEmails = $contact_emails;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.repository'), $container
      ->get('entity_type.bundle.info'), $container
      ->get('datetime.time'), $container
      ->get('contact_emails.helper'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $contact_form = $this
      ->getContactForm($form_state);
    $email_fields = FALSE;
    $reference_fields = FALSE;
    if ($contact_form) {

      // Load fields related to this contact form.
      $email_fields = $this->contactEmails
        ->getContactFormFields($contact_form
        ->id(), 'email');
      $reference_fields = $this->contactEmails
        ->getContactFormFields($contact_form
        ->id(), 'entity_reference');

      // Store the contact form id.
      $form['contact_form']['widget'][0]['target_id']['#type'] = 'hidden';
      $form['contact_form']['widget'][0]['target_id']['#value'] = $contact_form
        ->id();
    }

    // Add validation to the subject.
    $form['subject']['widget'][0]['value']['#element_validate'][] = 'token_element_validate';
    $form['subject']['widget'][0]['value']['#token_types'][] = 'contact_message';
    $form['subject']['widget'][0]['value']['#description'] = $this
      ->t('The subject of the email. To add a variable, click within the above field and then click the "Browse available tokens" link below. You will find the fields of your forms within Contact Message. Note that tokens that produce html markup are not supported for an email subject.');

    // Token help for body field.
    $form['token_help_subject'] = [
      '#theme' => 'token_tree_link',
      '#weight' => -9,
      '#token_types' => [
        'contact_message',
      ],
    ];

    // Body field.
    $form['message']['widget'][0] = array_merge($form['message']['widget'][0], [
      '#title' => $this
        ->t('Message'),
      '#description' => $this
        ->t('The body of the email.'),
      '#element_validate' => [
        'token_element_validate',
      ],
      '#token_types' => [
        'contact_message',
      ],
    ]);

    // Token help for body field.
    $form['token_help_body'] = [
      '#theme' => 'token_tree_link',
      '#weight' => -1,
      '#token_types' => [
        'contact_message',
      ],
    ];

    // Recipient type.
    $form['recipient_type']['widget'][0]['value'] = array_merge($form['recipient_type']['widget'][0]['value'], [
      '#type' => 'select',
      '#options' => [
        'default' => $this
          ->t('The website from address'),
        'submitter' => $this
          ->t('The submitter of the form'),
        'field' => $this
          ->t('The value of a specific field in the form'),
        'reference' => $this
          ->t('The value of a specific field in an entity reference'),
        'manual' => $this
          ->t('Specific email address(es)'),
      ],
      '#size' => NULL,
      '#description' => $this
        ->t('Choose how to determine who the email recipient(s) should be.'),
    ]);

    // Recipient is a value in a field.
    if ($email_fields) {
      $form['recipient_field']['widget'][0]['value'] = array_merge($form['recipient_field']['widget'][0]['value'], [
        '#type' => 'select',
        '#options' => $email_fields,
        '#description' => $this
          ->t('Send the email to the value of this field.'),
        '#size' => NULL,
      ]);
    }
    else {
      $form['recipient_field']['widget'][0]['value'] = array_merge($form['recipient_field']['widget'][0]['value'], [
        '#type' => 'item',
        '#title' => $this
          ->t('No fields available'),
        '#description' => $this
          ->t('You must have at least one email field available to use this option.'),
        '#size' => NULL,
      ]);
    }
    $form['recipient_field']['widget'][0]['value'] = array_merge($form['recipient_field']['widget'][0]['value'], [
      '#states' => [
        'visible' => [
          ':input[name="recipient_type[0][value]"]' => [
            'value' => 'field',
          ],
        ],
      ],
    ]);

    // Recipient is a value of a reference field.
    if ($reference_fields) {
      $form['recipient_reference']['widget'][0]['value'] = array_merge($form['recipient_reference']['widget'][0]['value'], [
        '#type' => 'select',
        '#options' => $reference_fields,
        '#description' => $this
          ->t('Send the email to the value of this referenced field.'),
        '#size' => NULL,
      ]);
    }
    else {
      $form['recipient_reference']['widget'][0]['value'] = array_merge($form['recipient_reference']['widget'][0]['value'], [
        '#type' => 'item',
        '#title' => $this
          ->t('No fields available'),
        '#description' => $this
          ->t('You must have at least one referenced entity available that has at least one email field available to use this option.'),
      ]);
    }
    $form['recipient_reference']['widget'][0]['value'] = array_merge($form['recipient_reference']['widget'][0]['value'], [
      '#states' => [
        'visible' => [
          ':input[name="recipient_type[0][value]"]' => [
            'value' => 'reference',
          ],
        ],
      ],
    ]);

    // Recipient is manually set.
    $form['recipients']['widget'][0]['value'] = array_merge($form['recipients']['widget'][0]['value'], [
      '#states' => [
        'visible' => [
          ':input[name="recipient_type[0][value]"]' => [
            'value' => 'manual',
          ],
        ],
      ],
      '#description' => $this
        ->t('Enter one or more recipients, separating multiple by commas.'),
    ]);

    // Recipient type.
    $form['reply_to_type']['widget'][0]['value'] = array_merge($form['reply_to_type']['widget'][0]['value'], [
      '#type' => 'select',
      '#options' => [
        'default' => $this
          ->t('Email replies should go to the website from email address (default)'),
        'submitter' => $this
          ->t('Email replies should go to the submitter of the form'),
        'field' => $this
          ->t('Email replies should go to the value of a specific field in the form'),
        'reference' => $this
          ->t('Email replies should go to the value of a specific field in an entity reference'),
        'manual' => $this
          ->t('Email replies should go a specific email address'),
      ],
      '#size' => NULL,
      '#description' => $this
        ->t('Choose how to determine where email replies should be sent.'),
    ]);

    // Reply-to is a value in a field.
    if ($email_fields) {
      $form['reply_to_field']['widget'][0]['value'] = array_merge($form['reply_to_field']['widget'][0]['value'], [
        '#type' => 'select',
        '#options' => $email_fields,
        '#description' => $this
          ->t('Email replies should go to the value of this field. Please note that if the field is not required and is left blank by the user, the reply-to will be set as the default website email instead.'),
        '#size' => NULL,
      ]);
    }
    else {
      $form['reply_to_field']['widget'][0]['value'] = array_merge($form['reply_to_field']['widget'][0]['value'], [
        '#type' => 'item',
        '#title' => $this
          ->t('No fields available'),
        '#description' => $this
          ->t('You must have at least one email field available to use this option.'),
      ]);
    }
    $form['reply_to_field']['widget'][0]['value'] = array_merge($form['reply_to_field']['widget'][0]['value'], [
      '#states' => [
        'visible' => [
          ':input[name="reply_to_type[0][value]"]' => [
            'value' => 'field',
          ],
        ],
      ],
    ]);

    // Recipient is a value of a reference field.
    if ($reference_fields) {
      $form['reply_to_reference']['widget'][0]['value'] = array_merge($form['reply_to_reference']['widget'][0]['value'], [
        '#type' => 'select',
        '#options' => $reference_fields,
        '#description' => $this
          ->t('Email replies should go to the value of this reference field. Please note that if the field is not required and is left blank by the user, the reply-to will be set as the default website email instead.'),
        '#size' => NULL,
      ]);
    }
    else {
      $form['reply_to_reference']['widget'][0]['value'] = array_merge($form['reply_to_reference']['widget'][0]['value'], [
        '#type' => 'item',
        '#title' => $this
          ->t('No fields available'),
        '#description' => $this
          ->t('You must have at least one referenced entity available that has at least one email field available to use this option.'),
      ]);
    }
    $form['reply_to_reference']['widget'][0]['value'] = array_merge($form['reply_to_reference']['widget'][0]['value'], [
      '#states' => [
        'visible' => [
          ':input[name="reply_to_type[0][value]"]' => [
            'value' => 'reference',
          ],
        ],
      ],
    ]);

    // Reply to is manually set.
    $form['reply_to_email']['widget'][0]['value'] = array_merge($form['reply_to_email']['widget'][0]['value'], [
      '#type' => 'email',
      '#states' => [
        'visible' => [
          ':input[name="reply_to_type[0][value]"]' => [
            'value' => 'manual',
          ],
        ],
      ],
      '#description' => $this
        ->t('Enter the reply to email recipient.'),
    ]);
    return $form;
  }

  /**
   * Get the contact form from the current request.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return \Drupal\contact\ContactFormInterface
   *   The contact form.
   */
  protected function getContactForm(FormStateInterface $form_state) {

    /** @var \Drupal\contact_emails\Entity\ContactEmailInterface $entity */
    $entity = $this->entity;
    if (!$entity
      ->get('contact_form')
      ->isEmpty()) {
      $contactForm = $entity
        ->get('contact_form')->target_id;
    }
    if (empty($contactForm) && $form_state
      ->hasValue('contact_form')) {
      $value = $form_state
        ->getValue('contact_form', NULL);
      $contactForm = is_array($value) ? $value[0]['target_id'] : NULL;
    }

    /** @var \Drupal\contact\ContactFormInterface $contactForm */
    if (empty($contactForm)) {
      $contactForm = \Drupal::routeMatch()
        ->getParameter('contact_form');
    }
    if (is_string($contactForm)) {
      $contactForm = ContactForm::load($contactForm);
    }
    return $contactForm;
  }

  /**
   * Get body potentially with format.
   */
  protected function getBody($form, $form_state) {

    /** @var \Drupal\contact_emails\Entity\ContactEmailInterface $entity */
    $entity = $this
      ->buildEntity($form, $form_state);
    return !$entity
      ->get('message')
      ->isEmpty() ? $entity
      ->get('message') : '';
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    parent::save($form, $form_state);
    $this
      ->messenger()
      ->addMessage($this
      ->t('Saved the %label contact email.', [
      '%label' => $this->entity
        ->label(),
    ]));
    $form_state
      ->setRedirect('entity.contact_email.collection', [
      'contact_form' => $form_state
        ->getValue('contact_form')[0]['target_id'],
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();

    // Require recipients if manual recipient type.
    if ($values['recipient_type'][0]['value'] == 'manual' && !$values['recipients'][0]['value']) {
      $form_state
        ->setErrorByName('recipients', $this
        ->t('Please add at least one recipient.'));
    }

    // Require field if field recipient type.
    if ($values['recipient_type'][0]['value'] == 'field' && !$values['recipient_field'][0]['value']) {
      $form_state
        ->setErrorByName('recipient_field', $this
        ->t('Please select a field with the email type to use this recipient type.'));
    }

    // Require reference field if reference recipient type.
    if ($values['recipient_type'][0]['value'] == 'reference' && !$values['recipient_reference'][0]['value']) {
      $form_state
        ->setErrorByName('recipient_reference', $this
        ->t('Please select a referenced field with the email type to use this recipient type.'));
    }

    // Require field if field reply-to type.
    if ($values['reply_to_type'][0]['value'] == 'field' && !$values['reply_to_field'][0]['value']) {
      $form_state
        ->setErrorByName('reply_to_field', $this
        ->t('Please select a field with the email type to use this reply-to type.'));
    }

    // Require email if email reply-to type.
    if ($values['reply_to_type'][0]['value'] == 'manual' && !$values['reply_to_email'][0]['value']) {
      $form_state
        ->setErrorByName('reply_to_email', $this
        ->t('Please enter a reply-to email address to use this reply-to type.'));
    }

    // Require reference field if reference reply to type.
    if ($values['reply_to_type'][0]['value'] == 'reference' && !$values['reply_to_reference'][0]['value']) {
      $form_state
        ->setErrorByName('reply_to_reference', $this
        ->t('Please select a reference field to use this reply-to type.'));
    }
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();

    /** @var \Drupal\contact_emails\ContactEmailStorageInterface $storage */
    $storage = \Drupal::entityTypeManager()
      ->getStorage('contact_email');

    // Warn the user if they are disabling the core contact emails for the
    // first time.
    $has_emails = $storage
      ->hasContactEmails($values['contact_form'][0]['target_id'], TRUE);
    if (!$has_emails && $this->entity
      ->isNew()) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('The default contact email from the form settings has been disabled and your new email has replaced it.'));
    }

    // Save the contact email and rebuild the cache.
    parent::submitForm($form, $form_state);
    $this->contactEmails
      ->rebuildCache();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContactEmailForm::$contactEmails protected property Drupal\contact_emails\ContactEmails definition.
ContactEmailForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
ContactEmailForm::form public function Gets the actual form array to be built. Overrides ContentEntityForm::form
ContactEmailForm::getBody protected function Get body potentially with format.
ContactEmailForm::getContactForm protected function Get the contact form from the current request.
ContactEmailForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
ContactEmailForm::submitForm public function Overrides ContentEntityForm::submitForm
ContactEmailForm::validateForm public function Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level… Overrides ContentEntityForm::validateForm
ContactEmailForm::__construct public function Constructs a ContentEntityForm object. Overrides ContentEntityForm::__construct
ContentEntityForm::$entity protected property The entity being used by this form. Overrides EntityForm::$entity 9
ContentEntityForm::$entityRepository protected property The entity repository service.
ContentEntityForm::$entityTypeBundleInfo protected property The entity type bundle info service.
ContentEntityForm::$time protected property The time service.
ContentEntityForm::addRevisionableFormFields protected function Add revision form fields if the entity enabled the UI.
ContentEntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity 3
ContentEntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties Overrides EntityForm::copyFormValuesToEntity
ContentEntityForm::flagViolations protected function Flags violations for the current form. 4
ContentEntityForm::getBundleEntity protected function Returns the bundle entity of the entity, or NULL if there is none.
ContentEntityForm::getEditedFieldNames protected function Gets the names of all fields edited in the form. 4
ContentEntityForm::getFormDisplay public function Gets the form display. Overrides ContentEntityFormInterface::getFormDisplay
ContentEntityForm::getFormLangcode public function Gets the code identifying the active form language. Overrides ContentEntityFormInterface::getFormLangcode
ContentEntityForm::getNewRevisionDefault protected function Should new revisions created on default.
ContentEntityForm::init protected function Initializes the form state and the entity before the first form build. Overrides EntityForm::init 1
ContentEntityForm::initFormLangcodes protected function Initializes form language code values.
ContentEntityForm::isDefaultFormLangcode public function Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface::isDefaultFormLangcode
ContentEntityForm::prepareEntity protected function Prepares the entity object before the form is built first. Overrides EntityForm::prepareEntity 1
ContentEntityForm::setFormDisplay public function Sets the form display. Overrides ContentEntityFormInterface::setFormDisplay
ContentEntityForm::showRevisionUi protected function Checks whether the revision form fields should be added to the form.
ContentEntityForm::updateChangedTime public function Updates the changed time of the entity.
ContentEntityForm::updateFormLangcode public function Updates the form language to reflect any change to the entity language.
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
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
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.