2

I really got quite far on this issue. Using Drupal 8's Modal API. Having a button in a block that triggers the modal with Drupal's language switcher inside. Everything looks fine EXCEPT for the URLs this modal returns. Every URL gets appended with ?ajax_form=1&_wrapper_format=html which breaks the whole functionality. For example http://d8.dev/fr/node-41-article?ajax_form=1&_wrapper_format=html.

I also tried it with a Controller instead of a Form. But then the URLs look even worse, since then they only take the controller path to create the langswitch URLs.

I already started to guess I'd need to start over using a more independent approach. But maybe you folks know a way to get it working with my current approach? Is there a way I can simply cut off the query? Here is what I have so far:

<?php

/**
 * @file
 * Contains \Drupal\langswitch_modal\Form\LangswitchModal.
 */

namespace Drupal\langswitch_modal\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\OpenModalDialogCommand;

/**
 * Class LangswitchModal.
 *
 * @package Drupal\langswitch_modal\Form
 */
class LangswitchModal extends FormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#attached']['library'][] = 'core/drupal.dialog.ajax';

    $form['actions']['#type']  = 'actions';
    $form['actions']['submit'] = [
      '#type'  => 'submit',
      '#value' => $this->t('Switch language'),
      '#ajax'  => [
        'callback' => '::open_modal',
      ],
    ];

    return $form;
  }

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

  }

  public function open_modal(&$form, FormStateInterface $form_state) {

    $block   = \Drupal\block\BlockViewBuilder::lazyBuilder('languageswitcher', 'full');
    $render  = \Drupal::service('renderer')->renderPlain($block);
    $title   = $this->t('Choose language');
    $content = $render;
    $options = [
      'dialogClass' => 'popup-dialog-class',
      'width'       => '300',
      'height'      => '300',
    ];

    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand($title, $content, $options));

    return $response;
  }
}
1

Got it! All I needed was a little JS to get rid of the query:

$(document).ajaxComplete(function() {
  var $link = $('a.language-link');
  $link.each(function(i,el){
    $(el).attr('href', $(el).attr('href').split('?')[0]);
  });
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.