You are here

public function ContactPopupBlock::build in Contact Form Popup 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/ContactPopupBlock.php, line 136

Class

ContactPopupBlock
Provides a 'ContactPopupBlock' block.

Namespace

Drupal\contact_poup\Plugin\Block

Code

public function build() {
  $build = [];
  $config = $this
    ->getConfiguration();
  if (empty($config['contact_form'])) {
    return $build;
  }
  $storage_contact_form = $this->entityTypeManager
    ->getStorage('contact_form');
  $contact_form = $storage_contact_form
    ->load($config['contact_form']);
  if (empty($contact_form)) {
    return $build;
  }
  $id = $contact_form
    ->id();
  $options = array(
    'attributes' => array(
      'class' => array(
        'use-ajax',
        'contact-form',
      ),
      'data-dialog-type' => 'modal',
    ),
  );

  // Personnal contact form.
  if ($id === 'personal') {
    if ($user = $this->routeMatch
      ->getParameter('user')) {
      $contact_form_url = Url::fromRoute('entity.user.contact_form', [
        'user' => $user
          ->id(),
      ], $options);

      // Cache vary by url if we have a personal contact form.
      $build['#cache']['contexts'][] = 'url';
    }
    else {
      return $build;
    }
  }
  else {
    $contact_form_url = $contact_form
      ->toUrl('canonical', $options);
  }
  $contact_form_title = $contact_form
    ->label();
  $title = empty($config['link_title']) ? $contact_form_title : $config['link_title'];
  $link = Link::fromTextAndUrl($title, $contact_form_url);
  $build['contact_form'] = [
    '#theme' => 'contact_popup_block',
    '#link' => $link,
    '#contact_form' => $contact_form,
  ];
  $build['contact_form']['#attached']['library'][] = 'core/drupal.dialog.ajax';
  $build['#cache']['contexts'][] = 'user.permissions';
  return $build;
}