You are here

class MandrillTemplateMapForm in Mandrill 8

Form controller for the MandrillTemplateMap entity edit form.

Hierarchy

Expanded class hierarchy of MandrillTemplateMapForm

File

modules/mandrill_template/src/Form/MandrillTemplateMapForm.php, line 21
Contains \Drupal\mandrill_template\Form\MandrillTemplateMapForm.

Namespace

Drupal\mandrill_template\Form
View source
class MandrillTemplateMapForm extends EntityForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);

    /* @var $map \Drupal\mandrill_template\Entity\MandrillTemplateMap */
    $map = $this->entity;

    /* @var $mandrill_api \Drupal\mandrill\MandrillAPI */
    $mandrill_api = \Drupal::service('mandrill.api');
    $templates = $mandrill_api
      ->getTemplates();
    $form['label'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#default_value' => $map->label,
      '#description' => t('The human-readable name of this Mandrill Template Map entity.'),
      '#required' => TRUE,
    );
    $form['id'] = array(
      '#type' => 'machine_name',
      '#default_value' => $map->id,
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
      '#machine_name' => array(
        'source' => array(
          'label',
        ),
        'exists' => array(
          $this,
          'exists',
        ),
      ),
      '#description' => t('A unique machine-readable name for this Mandrill Template Map entity. It must only contain lowercase letters, numbers, and underscores.'),
      '#disabled' => !$map
        ->isNew(),
    );
    $form['map_settings'] = array(
      '#type' => 'fieldset',
      '#title' => t('Template Map Settings'),
      '#collapsible' => FALSE,
      '#prefix' => '<div id="template-wrapper">',
      '#suffix' => '</div>',
    );
    $template_names = array();
    foreach ($templates as $template) {
      $template_names[$template['slug']] = $template;
    }

    // Check if the currently configured template still exists.
    if (!empty($map->template_id) && !array_key_exists($map->template_id, $template_names)) {
      $this
        ->messenger()
        ->addWarning(t('The configured Mandrill template is no longer available, please select a valid one.'));
    }
    if (!empty($templates)) {
      $options = array(
        '' => t('-- Select --'),
      );
      foreach ($templates as $template) {
        $options[$template['slug']] = $template['name'];
      }
      $form['map_settings']['template_id'] = array(
        '#type' => 'select',
        '#title' => t('Email Template'),
        '#description' => t('Select a Mandrill template.'),
        '#options' => $options,
        '#default_value' => isset($map->template_id) ? $map->template_id : '',
        '#required' => TRUE,
        '#ajax' => array(
          'callback' => '::template_callback',
          'wrapper' => 'template-wrapper',
          'method' => 'replace',
          'effect' => 'fade',
          'progress' => array(
            'type' => 'throbber',
            'message' => t('Retrieving template information.'),
          ),
        ),
      );
      $form_template_id = $form_state
        ->getValue('template_id');
      if (!$form_template_id && isset($map->mandrill_template_map_entity_id)) {
        $form_template_id = $map->template_id;
      }
      if ($form_template_id) {
        $regions = array(
          '' => t('-- Select --'),
        ) + $this
          ->parseTemplateRegions($template_names[$form_template_id]['publish_code']);
        $form['map_settings']['main_section'] = array(
          '#type' => 'select',
          '#title' => t('Template region'),
          '#description' => t('Select the template region to use for email content. <i>Note that you can populate more regions by attaching an array to your message with the index "mandrill_template_content", using region names as indexes to the content for that region.'),
          '#options' => $regions,
          '#default_value' => isset($map->main_section) ? $map->main_section : '',
          '#required' => TRUE,
        );
      }
      $usable_keys = mandrill_template_map_usage();
      $module_names = mandrill_get_module_key_names();
      $mandrill_in_use = FALSE;
      $available_modules = FALSE;
      $mailsystem_options = array(
        '' => t('-- None --'),
      );
      foreach ($usable_keys as $key => $sys) {
        $mandrill_in_use = TRUE;
        if ($sys === NULL || isset($map) && $sys == $map->mandrill_template_map_entity_id) {
          $mailsystem_options[$key] = $module_names[$key];
          $available_modules = TRUE;
        }
      }
      if ($mandrill_in_use) {
        $form['mailsystem_key'] = array(
          '#type' => 'select',
          '#title' => t('Email key'),
          '#description' => t('Select a module and mail key to use this template for outgoing email. Note that if an email has been selected in another Template Mapping, it will not appear in this list. These keys are defined through the %MailSystem interface.', array(
            '%MailSystem' => Link::fromTextAndUrl(t('MailSystem'), Url::fromRoute('mailsystem.settings'))
              ->toString(),
          )),
          '#options' => $mailsystem_options,
          '#default_value' => isset($map->mailsystem_key) ? $map->mailsystem_key : '',
        );
        if (!$available_modules) {
          $this
            ->messenger()
            ->addWarning(t("All email-using modules that have been assigned to Mandrill are already assigned to other template maps"));
        }
      }
      if (!$mandrill_in_use) {
        $this
          ->messenger()
          ->addWarning(t("You have not assigned any Modules to use Mandrill: to use this template, make sure Mandrill is assigned in Mailsystem."));
      }
    }
    else {
      $form['email_options']['#description'] = t('The template selection is only available if the Mandrill API is correctly configured and available.');
    }
    return $form;
  }

  /**
   * AJAX callback handler for MandrillTemplateMapForm.
   */
  public function template_callback(&$form, FormStateInterface $form_state) {
    return $form['map_settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {

    /* @var $template_map \Drupal\mandrill_template\Entity\MandrillTemplateMap */
    $template_map = $this
      ->getEntity();
    $template_map
      ->save();
    \Drupal::service('router.builder')
      ->setRebuildNeeded();
    $form_state
      ->setRedirect('mandrill_template.admin');
  }
  public function exists($id) {
    $entity = $this->entityTypeManager
      ->getStorage('mandrill_template_map')
      ->getQuery()
      ->condition('id', $id)
      ->execute();
    return (bool) $entity;
  }

  /**
   * Parses a Mandrill template to extract its regions.
   */
  private function parseTemplateRegions($html, $tag = 'mc:edit') {
    $instances = array();
    $offset = 0;
    $inst = NULL;
    while ($offset = strpos($html, $tag, $offset)) {
      $start = 1 + strpos($html, '"', $offset);
      $length = strpos($html, '"', $start) - $start;
      $inst = substr($html, $start, $length);
      $instances[$inst] = $inst;
      $offset = $start + $length;
    }
    return $instances;
  }

}

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
EntityForm::$entity protected property The entity being used by this form. 7
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::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
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::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
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::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
MandrillTemplateMapForm::exists public function
MandrillTemplateMapForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
MandrillTemplateMapForm::parseTemplateRegions private function Parses a Mandrill template to extract its regions.
MandrillTemplateMapForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
MandrillTemplateMapForm::template_callback public function AJAX callback handler for MandrillTemplateMapForm.
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.