You are here

class MailingListForm in Mailing List 8

Form handler for mailing list forms.

Hierarchy

Expanded class hierarchy of MailingListForm

File

src/Form/MailingListForm.php, line 14

Namespace

Drupal\mailing_list\Form
View source
class MailingListForm extends BundleEntityFormBase {

  /**
   * The entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface
   */
  protected $entityManager;

  /**
   * Constructs the MailingListForm object.
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   */
  public function __construct(EntityManagerInterface $entity_manager) {
    $this->entityManager = $entity_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.manager'));
  }

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

    /** @var \Drupal\mailing_list\MailingListInterface $mailing_list */
    $mailing_list = $this->entity;
    $form['#title'] = $this->operation == 'add' ? $this
      ->t('Add a new mailing list') : $this
      ->t('Edit %label mailing list', [
      '%label' => $mailing_list
        ->label(),
    ]);
    $form['label'] = [
      '#title' => $this
        ->t('Name'),
      '#type' => 'textfield',
      '#default_value' => $mailing_list
        ->label(),
      '#description' => $this
        ->t('The human-readable name of this mailing list. This name must be unique.'),
      '#required' => TRUE,
      '#size' => 30,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $mailing_list
        ->id(),
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
      '#machine_name' => [
        'exists' => [
          'Drupal\\mailing_list\\Entity\\MailingList',
          'load',
        ],
        'source' => [
          'label',
        ],
      ],
      '#description' => $this
        ->t('A unique machine-readable name for this mailing list. It must only contain lowercase letters, numbers, and underscores.'),
    ];
    $form['description'] = [
      '#title' => $this
        ->t('Description'),
      '#type' => 'textarea',
      '#rows' => 2,
      '#default_value' => $mailing_list
        ->getDescription(),
      '#description' => $this
        ->t('This text will be displayed on subscriptions management pages for this mailing list.'),
    ];
    $form['help'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Explanation or submission guidelines'),
      '#rows' => 2,
      '#default_value' => $mailing_list
        ->getHelp(),
      '#description' => $this
        ->t('Help information shown to the user when creating a new subscription on this list.'),
    ];
    $form['additional_settings'] = [
      '#type' => 'vertical_tabs',
    ];
    $form['control'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Subscription control'),
      '#open' => TRUE,
      '#group' => 'additional_settings',
    ];
    $form['control']['cross_access'] = [
      '#title' => $this
        ->t('Allow subscription cross access'),
      '#description' => $this
        ->t('Grant access to non-owned subscriptions through the subscription management hashed URL.'),
      '#type' => 'checkbox',
      '#default_value' => $mailing_list
        ->isCrossAccessAllowed(),
    ];
    $form['control']['form_destination'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Form destination'),
      '#options' => [
        '' => $this
          ->t('- Default -'),
        'canonical' => $this
          ->t('View subscription'),
        'edit-form' => $this
          ->t('Edit subscription'),
        'manage' => $this
          ->t('Manage subscriptions'),
      ],
      '#description' => $this
        ->t('Where to go after the subscription is created.'),
      '#default_value' => $mailing_list
        ->getFormDestination(),
    ];
    $form['control']['max_per_user'] = [
      '#title' => $this
        ->t('Limit per user'),
      '#description' => $this
        ->t('Max allowed subscriptions per user. Enter 0 for no limit.'),
      '#type' => 'number',
      '#default_value' => $mailing_list
        ->getLimitByUser() ?: 0,
      '#group' => 'additional_settings',
    ];
    $form['control']['max_per_email'] = [
      '#title' => $this
        ->t('Limit per email'),
      '#description' => $this
        ->t('Max allowed subscriptions per email address. Enter 0 for no limit.'),
      '#type' => 'number',
      '#default_value' => $mailing_list
        ->getLimitByEmail() ?: 0,
      '#group' => 'additional_settings',
    ];
    $secs_per_week = 7 * 24 * 60 * 60;
    $options = [
      $secs_per_week => $this
        ->t('1 week'),
    ];
    for ($i = 2; $i <= 7; $i++) {
      $options[$secs_per_week * $i] = $this
        ->t('@count weeks', [
        '@count' => $i,
      ]);
    }
    for ($i = 2; $i <= 11; $i++) {
      $options[round($i * 4.33)] = $this
        ->t('@count months', [
        '@count' => $i,
      ]);
    }
    $options[$secs_per_week * 52] = $this
      ->t('1 year');
    for ($i = 2; $i <= 5; $i++) {
      $options[$secs_per_week * 52 * $i] = $this
        ->t('@count years', [
        '@count' => $i,
      ]);
    }
    $options[0] = $this
      ->t('- Do not purge -');
    $form['control']['inactive_subscriptions_liftime'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Inactive subscriptions lifetime'),
      '#description' => $this
        ->t('Inactive subscriptions older than this value will be purged from database.'),
      '#options' => $options,
      '#default_value' => $mailing_list
        ->getInactiveLifetime() ?: 0,
      '#group' => 'additional_settings',
    ];
    $form['messages'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Subscription operation messages'),
      '#group' => 'additional_settings',
    ];
    $form['messages']['subscription_message'] = [
      '#type' => 'textarea',
      '#title' => t('On subscription message'),
      '#description' => $this
        ->t('Message to the subscriber after a new subscription has done.'),
      '#rows' => 2,
      '#default_value' => $mailing_list
        ->getOnSubscriptionMessage(),
    ];
    $form['messages']['cancellation_message'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('On cancellation message'),
      '#description' => $this
        ->t('Message to the subscriber on subscription cancellation.'),
      '#rows' => 2,
      '#default_value' => $mailing_list
        ->getOnCancellationMessage(),
    ];
    return $this
      ->protectBundleIdElement($form);
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = t('Save mailing list');
    $actions['delete']['#value'] = t('Delete mailing list');
    return $actions;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $id = trim($form_state
      ->getValue('id'));

    // '0' is invalid, to safe empty check.
    if ($id == '0') {
      $form_state
        ->setErrorByName('id', $this
        ->t("Invalid machine-readable name. Enter a name other than %invalid.", [
        '%invalid' => $id,
      ]));
    }
    $max_per_user = intval($form_state
      ->getValue('max_per_user'));
    if ($max_per_user < 0) {
      $form_state
        ->setErrorByName('max_per_user', $this
        ->t("Limit per user must be an number greater or equal than 0."));
    }
    $max_per_email = intval($form_state
      ->getValue('max_per_email'));
    if ($max_per_email < 0) {
      $form_state
        ->setErrorByName('max_per_email', $this
        ->t("Limit per email must be an number greater or equal than 0."));
    }
  }

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

    /** @var \Drupal\mailing_list\Entity\MailingList $mailing_list */
    $mailing_list = $this->entity;
    $status = $mailing_list
      ->save();
    $t_args = [
      '%name' => $mailing_list
        ->label(),
    ];
    if ($status == SAVED_UPDATED) {
      drupal_set_message(t('The mailing list %name has been updated.', $t_args));
    }
    elseif ($status == SAVED_NEW) {
      drupal_set_message(t('The mailing list %name has been added.', $t_args));
      $context = array_merge($t_args, [
        'link' => $mailing_list
          ->toLink($this
          ->t('View'), 'collection')
          ->toString(),
      ]);
      $this
        ->logger('mailing_list')
        ->notice('Added mailing list %name.', $context);
    }
    $this->entityManager
      ->clearCachedFieldDefinitions();
    $form_state
      ->setRedirectUrl($mailing_list
      ->toUrl('collection'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BundleEntityFormBase::protectBundleIdElement protected function Protects the bundle entity's ID property's form element against changes.
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::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::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.
MailingListForm::$entityManager protected property The entity manager.
MailingListForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
MailingListForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MailingListForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
MailingListForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
MailingListForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
MailingListForm::__construct public function Constructs the MailingListForm object.
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.