Programmatically creating custom block types for Panels

Posted on 03/03/2017

The most potent Drupal module for creating very complex layouts is definitely Panels. It integrates with a lot of other parts of your Drupal site, so you can show views, nodes, webforms, blocks, and pretty much anything else you can think of. Page builder is very easy to use and allows administrators visual representation of complex pages.

One of the limitations I faced multiple times is lack of any customization of the generic "Custom content" block. However, this is easily achieved with a custom module. In this article, I will show you how to provide a custom CTools content type in your custom module and use it with Panels.

The code in this article will work only for Drupal 7. Article for D8 will come later.

So, when would you need a custom CTools content type? Basically any time when you wish that the "Custom content" provided by Panels had more fields so you can manipulate better the output. With a custom content type you can define any number of configurable fields, preprocess those values and render the output.

Before starting, it is good to explain why do we actually need to integrate with CTools instead of Panels. The reason for this is that Panels builds a lot of its functionality on top of CTools and custom content types (which are actually blocks you can add to a panel) are provided by CTools.

First thing to do is to implement the hook_ctools_plugin_directory() and provide the directory in our custom module where we will store our content types. I recommend making this as self as explanatory as possible and storing the new content type in /plugins/ctools/content_types. Also, to avoid name collision with other modules, prefix everything with the machine name of your module.

  1. /**
  2.  * Implement hook_ctools_plugin_directory().
  3.  */
  4. function YOUR_MODULE_ctools_plugin_directory($owner, $plugin_type) {
  5.   if ($owner == 'ctools' && $plugin_type == 'content_types') {
  6.     return 'plugins/ctools/content_types';
  7.   }
  8. }

Next, we will create the plugins/ctools/content_types directories in your custom module. Each content type should be in a separate file. In our case, we will name the content type "Teaser block with image", so the file name I chose is YOUR_MODULE_pane_teaser_block_with_image.inc. This file should contain plugin information and certain hooks that will be used for configuration form, storing the settings and rendering.

Plugin declaration provides basic information to CTools, such as name and description, and lists callbacks that should be used for various aspects of your custom content type. The code should be placed at the top of your plugin file, outside of any function or class.

  1. /**
  2.  * Plugin declaration.
  3.  */
  4. $plugin = array(
  5.   'title' => t('Custom block'),
  6.   'description' => t('Displays a custom block with customizable fields.'),
  7.   // This is the callback to the administrative form where we will show the
  8.   // configuration form.
  9.   'edit form' => 'YOUR_MODULE_pane_teaser_block_with_image_edit_form',
  10.   // This is the callback used for rendering the block itself. Here you can
  11.   // include any preprocessing logic you need.
  12.   'render callback' => 'YOUR_MODULE_pane_teaser_block_with_image_render',
  13.   // Default setting values are provided here.
  14.   'defaults' => array(
  15.     'textfield' => NULL,
  16.     'checkboxes' => NULL,
  17.     'select' => t('See More'),
  18.     'content' => array('filter' => '', 'value' => ''),
  19.   ),
  20.   // This means that the block is available in all contexts - nodes, blocks, etc.
  21.   'all contexts' => TRUE,
  22. );

After this, we will create the edit form for administrators. This uses Drupal's Form API, so all elements are standardized. The only difference is that block settings will not be fetched from variable storage (using variable_get(), like you would do with regular blocks and admin settings forms) but instead you would get everything from the $conf variable passed to your form. Here's an example:

  1. /**
  2.  * Administrative form callback.
  3.  */
  4. function YOUR_MODULE_pane_teaser_block_with_image_edit_form($form, &$form_state) {
  5.   $conf = $form_state['conf'];
  6.  
  7.   // You can start adding the fields to the $form variable using Drupal Form API.
  8.   //
  9.   // Here are some example fields:
  10.   $form['textfield'] = array(
  11.     '#type' => 'textfield',
  12.     '#title' => t('Text field'),
  13.     '#default_value' => $conf['textfield'],
  14.     '#required' => TRUE,
  15.   );
  16.   $form['select'] = array(
  17.     '#type' => 'select',
  18.     '#title' => t('Select box'),
  19.     '#default_value' => $conf['select'],
  20.     '#required' => TRUE,
  21.     '#options' => array(
  22.       'option1' => t('Option @number', array('@number' => 1)),
  23.       'option2' => t('Option @number', array('@number' => 2)),
  24.       'option3' => t('Option @number', array('@number' => 3)),
  25.       'option4' => t('Option @number', array('@number' => 4)),
  26.       'option5' => t('Option @number', array('@number' => 5)),
  27.     ),
  28.   );
  29.   $form['checkboxes'] = array(
  30.     '#type' => 'checkboxes',
  31.     '#title' => t('Checkboxes'),
  32.     '#default_value' => $conf['checkboxes'],
  33.     '#required' => TRUE,
  34.     '#options' => array(
  35.       'checkbox1' => t('Checkbox @number', array('@number' => 1)),
  36.       'checkbox2' => t('Checkbox @number', array('@number' => 2)),
  37.       'checkbox3' => t('Checkbox @number', array('@number' => 3)),
  38.       'checkbox4' => t('Checkbox @number', array('@number' => 4)),
  39.       'checkbox5' => t('Checkbox @number', array('@number' => 5)),
  40.     ),
  41.   );
  42.   $editor_field = $conf['content'];
  43.   $form['content'] = array(
  44.     '#type' => 'text_format',
  45.     '#base_type' => 'textarea',
  46.     '#title' => t('Formatted input'),
  47.     '#default_value' => $editor_field['value'],
  48.     '#format' => $editor_field['format'],
  49.   );
  50.  
  51.   return $form;
  52. }

The submit callback will be pretty straightforward; we can store everything based on the keys so there is no need to handle each field separately.

  1. /**
  2.  * Submit callback.
  3.  */
  4. function YOUR_MODULE_pane_teaser_block_with_image_edit_form_submit(&$form, &$form_state) {
  5.   foreach (array_keys($form_state['plugin']['defaults']) as $key) {
  6.     if (isset($form_state['values'][$key])) {
  7.       $form_state['conf'][$key] = $form_state['values'][$key];
  8.     }
  9.   }
  10. }

Now comes the interesting part - rendering of the block. If you want to keep it clean, you can also declare your own template in hook_theme() of your module and just invoke here the theme() function instead. However, to keep this simple, I will just

  1. /**
  2.  * Render callback.
  3.  */
  4. function YOUR_MODULE_pane_teaser_block_with_image_render($subtype, $conf, $args, $contexts) {
  5.   // All settings are stored in the $conf variable, with field names as array keys.
  6.   // For example:
  7.   $text_field_value = $conf['textfield'];
  8.   $editor_field = $conf['content'];
  9.  
  10.   // Return value must be an object with title and content properties.
  11.   $block = new stdClass();
  12.   $block->title = NULL;
  13.   // Instead of compiling the content in a variable and passing it here, you can
  14.   // add hook_theme() implementation in your .module file and call theme() here
  15.   // instead. That way you can have the template as a separate file.
  16.   $block->content = 'Content';
  17.  
  18.   return $block;
  19. }

The example above just scratched the surface and presented the basics. There are a lot of other things you can do here, such as work with contexts, add file uploads, combine this with dynamic rules, etc. The best way to learn how these more complex scenarios are setup is to examine the code of content types shipped with CTools module.

Links