Search code examples
drupaladmindrupal-8

Add a popup in Drupal 8 admin


I want to create a popup that display example of possible usable tag in a textarea, I need it to be displayed on every content edition page on the admin.

What do I need to do to have that kind of block in the admin content edition page ?

Thanks.


Solution

  • I would create a module with:

    • A twig file containing the contents of the dialog.
    • A small JS file to show the dialog, using the jquery.dialog library included in Drupal 8.
    • Implement a hook_from_alter to attach the changes based on the form_ids.

    Like the following, which works on node edit forms, but is not thoroughly tested:

    file: templates/popuptag.html.twig

    <div style="display: none;">
      <div id="popuptag-dialog" title="Tag Usage">
       <p>The tag can be used at vero eos et accusamus et iusto odio
         dignissimos ducimus qui blanditiis praesentium voluptatum
         deleniti atque corrupti quos dolores et quas molestias
         excepturi sint occaecati cupiditate non provident, similique sunt.</p>
      </div>
    </div>
    

    file: js/popuptag.dialog.js

    (function ($) {
      'use strict';
      Drupal.behaviors.popuptag_dialog = {
        attach: function (context) {
          $( "#popuptag-dialog" ).dialog();
        }
      };
    })(jQuery);
    

    file: popuptag.module

    /**
     * Implements hook_theme().
     */
    function popuptag_theme() {
      return [
        'popuptag' => [
          'template'  => 'popuptag',
          'render element' => 'dialog',
        ],
      ];
    }
    
    /**
     * Implements hook_form_alter().
     */
    function popuptag_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
      // Add here other form_ids if needed
      if (in_array($form_id, ['node_page_edit_form'])) {
        $form['popuptag'] = [
          '#theme' => 'popuptag',
          '#form_id' => $form_id,
        ];
        $form["#attached"]["library"][] = 'popuptag/dialog';
      }
    
    }
    

    file: popuptag.libraries.yml

    dialog:
      js:
        js/popuptag.dialog.js: { minified: true }
      dependencies:
        - core/drupal.dialog
    

    file: popuptag.info.yml

    name: 'popuptag'
    type: module
    description: 'popuptag'
    core: 8.x
    package: 'Custom'