[Drupal] How to Implement Popups using Ctools Modal forms in your Drupal 7 Site

| | 2 min read

One such feature used widely throughout the site is the use of popups for alerting users. Popups are nothing new to web development. In fact Drupal provides multiple tools to create popups including the more widely used Colorbox plugin. For this project we chose to go with Ctools modal popup as it provided more options than Colorbox. Read on to know how to implement popups using Ctools.

Follow the steps below to implement the pop-ups

First we need to install Chaos tools module which contains the code for the popup. Next we need to identify the links and buttons on which we need to trigger the popup. Once we have identified the links we need to define those links using hook_menu. The page callback function of the menu definition would need to be created as per the following code. As it is a callback function you can give a suitable name respect the namespace of your site.

 


  /**
   * Custom  Page callback
   *
   */
  function custom_modal_callback() {
    ctools_include('ajax');
    ctools_include('modal');
    $form_state = array(
      'ajax' => TRUE,
      'title' => 'Title',
    );

    $output = ctools_modal_form_wrapper('custon_modal_form', $form_state);
    print ajax_render($output);
    drupal_exit();
  }

Once we have defined the callback then we would need to add the 'class ctools-use-modal' class for the link or button where we need to attach our modal dialog.

As we remain true to Drupal coding standards we used the Drupal l() function to generate the relevant links and added the class to the link using that function as shown below.


  l('click me', 'modal/link', array( 'attributes' => array('class' => array( 'ctools-use-modal' )) ));

Code explained:

ctools_include is used to include the two required parameters for defining the pop-up. The title will show as the title of the pop-up. If you have already defined a form elsewhere and would like to include it in the pop-up you can call it here using ctools_modal_form_wrapper.

If you find this article helpful , please feel free to share the article. Also, if you need any further assistance, please feel free to get in touch with us.