[Drupal] How to show a form in popup?

| | 2 min read

This tutorial shows you how to insert a form into a modal so it pops up on your site after a user clicks a link, without having to write any JavaScript at all. The functionality that supplies this is the CTools module and core ajax functionality in Drupal 7.

In this tutorial, we will create a page which has a single link on it. When clicked, a pop-up modal will show a form with a text box and submit button. When submitted, the modal will close and the text in text box will replace the text in the link.


Replace your link with the above code. Also you have to create a interface to the popup 'mymodule/nojs', the callback function is given below

 * Ajax menu callback.
function mymodule_callback($ajax) {
  if ($ajax) {
    $form_state = array(
      'ajax' => TRUE,
      'title' => t('MyModule Modal Form'),
    // Use ctools to generate ajax instructions for the browser to create
    // a form in a modal popup.
    $output = ctools_modal_form_wrapper('mymodule_form', $form_state);
    // If the form has been submitted, there may be additional instructions
    // such as dismissing the modal popup.
    if (!empty($form_state['ajax_commands'])) {
      $output = $form_state['ajax_commands'];
    // Return the ajax instructions to the browser via ajax_render().
    print ajax_render($output);
  else {
    return drupal_get_form('mymodule_form');

Then you have to build a form. You'll note that there is nothing special about the form itself and any Drupal form could therefore be used.

 * Drupal form to be put in a modal.
function mymodule_form($form, $form_state) {
  $form = array();
  $form['new_link_text'] = array(
    '#type' => 'textfield',
    '#title' => t('Link text'),
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  return $form;

In situations where you are not using your own form but some other in the Drupal system you might need to add additional ajax actions by including your own submission functions to the form.

 * Drupal form submit handler.
function mymodule_form_submit(&$form, &$form_state) {
  // Generate the new link using the submitted text value.
  $link = _mymodule_make_link($form_state['values']['new_link_text']);
  // Tell the browser to close the modal.
  $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
  // Tell the browser to replace the old link with the new one.
  $form_state['ajax_commands'][] = ajax_command_replace('#magical-modal-link', $link);