You are here

Drupal 8添加一个cancel按钮,用来关闭模态框

g089h515r806 的头像
Submitted by g089h515r806 on 星期五, 2019-11-15 09:23

作者:亚艾元技术部

Drupal8对ajax,模态框的支持非常友好,我们在客户的项目中,多次使用,为客户的项目提供了友好的用户体验。

客户想增加一个cancel按钮,点击cancel关闭模态框,我们是这样实现的,增加cancel按钮:


   if ($this->isDialog()) {
      $form['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('保存'),
        '#prefix' => '<div id="submit-button-container">',
        '#suffix' => '</div>',
        '#ajax' => array(
          'callback' => '::ajaxSubmit',
          'event' => 'click',
        ),
      ];

      $form['cancel'] = [
        '#type' => 'button',
        '#value' => $this->t('取消'),
        '#prefix' => '<div id="cancel-button-container">',
        '#suffix' => '</div>',

      ];	  
    }

追加我们的库

 $form['#attached']['library'][] = 'myuser/userform';


 

在我们的对应js文件中,增加js代码:

(function ($, Drupal) {
  //drupalSettings.fluffiness.cuddlySlider.baz
  //console.log(drupalSettings);
  'use strict';
  

  /**
   * Add custom js.
   *
   * @type {Drupal~behavior}
   *
   * @prop {Drupal~behaviorAttach} attach
   *
   */
  Drupal.behaviors.userform = {
    attach: function (context, settings) {

		$(context).find('#cancel-button-container input').click(function (e) {
             e.preventDefault();
			 $('.ui-dialog-titlebar .ui-dialog-titlebar-close').click();
		});	  

    }
  };

}(jQuery, Drupal));

这段js代码的作用,就是点击cancel按钮的时候,触发点击模态框右上角的关闭按钮。我们没有找到直接关闭模态框的函数,这样,也能很好的解决问题。


论坛:

Drupal版本: