You are here

public function SubscriptionBlock::build in Mailing List 8

Builds and returns the renderable array for this block plugin.

If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).

Return value

array A renderable array representing the content of the block.

Overrides BlockPluginInterface::build

See also

\Drupal\block\BlockViewBuilder

File

src/Plugin/Block/SubscriptionBlock.php, line 195

Class

SubscriptionBlock
Mailing list subscription blocks.

Namespace

Drupal\mailing_list\Plugin\Block

Code

public function build() {

  /** @var \Drupal\mailing_list\Form\SubscriptionForm $form_object */
  $form_object = $this->entityTypeManager
    ->getFormObject('mailing_list_subscription', 'block');

  // Add message.
  $form_object
    ->setMessage($this->configuration['message']);

  // Alter form ID.
  $form_object
    ->setCustomId($this->configuration['form_id']);

  // Set a new subscription entity as the entity form.

  /** @var \Drupal\mailing_list\SubscriptionInterface $entity */
  $entity = $this->entityTypeManager
    ->getStorage('mailing_list_subscription')
    ->create([
    'mailing_list' => $this->configuration['list'],
    'email' => $this->currentUser
      ->getEmail(),
  ]);
  $form_object
    ->setEntity($entity);

  // Add the form destination.
  $form_object
    ->setFormDestination($entity
    ->getList()
    ->getFormDestination());

  // Alter the default form submit button.
  $form = $this->formBuilder
    ->getForm($form_object);
  if ($form['actions']['submit']['#value'] == $this
    ->t('Save')
    ->render()) {
    $form['actions']['submit']['#value'] = $this
      ->t('Subscribe');
  }

  // Remove admin fields groups.
  unset($form['advanced']);
  unset($form['subscription_authoring']);
  unset($form['subscription_status']);

  // Block title is taken from the form title.
  if (isset($this->configuration['label']) && ($block_title = trim($this->configuration['label']))) {
    $form['#title'] = $block_title;
  }

  // Add manage subscription link.
  if ($this->configuration['manage_link']) {
    $manage_url = Url::fromRoute('entity.mailing_list_subscription.manage');
    if ($manage_url
      ->access()) {
      $form['manage_link'] = [
        '#type' => 'link',
        '#title' => $this
          ->t('Manage your subscriptions'),
        '#url' => $manage_url,
      ];
    }
  }
  return $form;
}