I created 2 block views:

message_activity_stream_timeline_public

message_activity_stream_timeline_private

I added the following code in the TWIG template of my homepage :

<div class="main-timeline">
{{ drupal_view('message_activity_stream_timeline_public', 'block_1') }}
{{ drupal_view('message_activity_stream_timeline_private', 'block_1') }}
</div>

I do not want to display the 2 blocks at the same time I want to create a toggle button and switch from block message_activity_stream_timeline_public to message_activity_stream_timeline_private with ajax and vice versa.

How can I do this ?

Comments

wombatbuddy’s picture

One possible way is to create a custom module with custom block and form.
A block will be display a form.
A form will be contains two elements: 'checkbox' (toggle button) and 'view'.
In the 'buildForm' method we check the value of 'checkbox' element and depend on it display corresponded view.
See the example:

Form class

<?php

namespace Drupal\my_module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class AjaxBlockForm.
 */
class AjaxBlockForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ajax_block_form';
  }

  /**
   * {@inheritdoc}
   */

  public function buildForm(array $form, FormStateInterface $form_state) {

    if ($form_state->getValue('toggle')) {
      $view_id = 'my_view_1';
      $display_id = 'page_1';
      $args = [];
    }
    else {
      $view_id = 'my_view_2';
      $display_id = 'page_1';
      $args = [];
    }

    $form['view'] = [
      '#type' => 'view',
      '#name' => $view_id,
      '#display_id' => $display_id,
      '#arguments' => $args,
      '#embed' => FALSE,
      '#cache' => [
        'keys' => [
          'view',
          $view_id,
          'display',
          $display_id,
        ],
      ],
    ];

    $form['view']['#id'] = 'view-wrapper-id';

    $form['toggle'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Toggle view'),
      '#ajax' => [
        'callback' => '::replaceView',
        'wrapper' => 'view-wrapper-id',
      ],
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function replaceView(array &$form, FormStateInterface $form_state) {
    return $form['view'];
  }


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

}

Block class 

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'DefaultBlock' block.
 *
 * @Block(
 *  id = "default_block",
 *  admin_label = @Translation("Default block"),
 * )
 */
class DefaultBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\AjaxBlockForm');
    return $form;
  }
}
zenimagine’s picture

Thanks for your help ;-)