Set Front Page from settings[.local].php in Drupal 8

When working on Drupal projects I usually need to set a static front page by referencing a Node’s ID. When working with different environments chances are high that Node ID varies from environment to environment.

Luckily we can easily override any configuration value in the settings file and thus have different values in settings.php than in settings.local.php. It’s simple as that: $config['']['page']['front'] = '/node/1';

Drupal: Add Body Class when Tabs are displayed

I had the urge to style various elements differently in case tabs (the ones generated by menu_local_tasks) are present on the page. Out of the box $tabs array isn’t available in html.tpl.php so I had to implement ‘ hook_preprocess_html’ and add my desired class to my array of body classes. Yay!

function THEMENAME_preprocess_html(&$vars, $hook) {
  // Make tabs available on html tpl
  $vars['tabs'] = menu_local_tabs();
  // if we have primary tabs, add an accoring body class
  if (!empty($vars['tabs']['#primary'])) {
    $vars['classes_array'][] = 'has-tabs';

Unmaintainable Block Admin Page in Drupal

When you have more than 100 Blocks things get messy on Drupal’s Block Admin Interface. If you ever went crazy because of weird issues when dragging and dropping blocks to change their weight and/or region you probably have hit Drupal’s internal limit of handling weights from -50 to +50 or otherwise said, 100 items.

It can be fixed by setting the variable drupal_weight_select_max to a higher value. This can be done in various ways, here’s how its implemented in a deploy script.

function dgm_deploy_update_7011() {
  variable_set('drupal_weight_select_max', 250);

Programmatically manipulate a Node’s field value upon saving 

For a recent project we needed to automatically change a Node’s field value upon saving with a computed value. For an unrelated reason we needed this value to be in a regular text field, so using Computed Field was off the table.

It turned out to be really simple to accomlish with a minimal amount of custom code.

 * Changes the value of field_marker to a string made up of the
 * Node's type and the value of it's category taxonomy term
 * Slashes will be replaced with deshes, spaces get removed
 * Must make sure that the following exists:
 *  - text field "field_marker"
 *  - node types "gesuch" and "angebot"
 *  - taxonomy reference field "field_category"

// Helper function to keep our code
function save_marker_category($node) {
  if($node->type == 'gesuch' || $node->type == 'angebot') {

    $find = array('/', ' ');
    $replace = array('-', '');

    $category_object = taxonomy_term_load($node->field_category['und'][0]['tid']);
    $category =  trim(strtolower(str_replace($find, $replace, $category_object->name)));

    $type = $node->type;
    $node->field_marker['und'][0]['value'] = $type.'_'.$category;

    // Save the new value
    field_attach_update('node', $node);

function MYMODULE_node_update($node) {

function MYMODULE_node_insert($node) {

HTML Template per Node Type

In case you need a different html.tpl.php on a per content type basis in Drupal 7

function THEME_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && $node->nid) {
    $vars['theme_hook_suggestions'][] = 'html__' . $node->type;

Custom Drupal Views Template breaks AJAX (updated)

I often create custom Views templates for my Drupal sites, for example to freely reposition exposed filters. Unfortunately, AJAX exposed filters in Views works only with a very strict markup hierarchy, and if your markup doesn’t match that scheme (.view-[view:id] > .view-filters > filters) it won’t work anymore

diff --git a/js/ajax_view.js b/js/ajax_view.js
index 7d54c67..f7f7ba9 100644
--- a/js/ajax_view.js
+++ b/js/ajax_view.js
@@ -57,7 +57,7 @@ Drupal.views.ajaxView = function(settings) {
   this.settings = settings;

   // Add the ajax to exposed forms.
-  this.$exposed_form = this.$view.children('.view-filters').children('form');
+  this.$exposed_form = this.$view.find('.view-filters form');
   this.$exposed_form.once(jQuery.proxy(this.attachExposedFormAjax, this));

   // Add the ajax to pagers.



Thanks to this patch that removed the selector dependence this is not needed anymore

Remove fields form content type programatically

Say you want to remove the body field from the page content type. Putting this code inside an updatescript will get the job done. Remember not to use field_delete_field() if you’re not sure if you still want to use the field anywhere else. It’s way safer to rely on field_delete_instance. Setting the second parameter to TRUE means it’s automatically going to clean up the field anyway if it is found to be the last instance.

$instance = field_info_instance('node', 'body', 'page');
field_delete_instance($instance, TRUE);

Translate Drupal Strings Programatically

One of the many issues one has to face when trying to do some proper deployment with Drupal (only up to version 7, that is) is custom localized strings. Fear no more! Instead of translating strings in the admin interface (/admin/config/regional/translate/translate) we can make use of the great Update Script Processor, thus put all our custom translations into code and happily version and deploy them. Yay!

  1. Install Update Script Processor
  2. A update Script that contains your localizations, e.G. $this->setLanguageWording('de', 'Telephone number', 'Telefonnummer');
  3. run drush updatescripts

Obviously, you should put that under version control and make sure your deployment process runs drush updatescripts after deploying to another environment.

Here’s a full example that translate the original strings Telephone number and Fax number to their German counterparts:

 * @file   0060-update-localization-string-test.php
 * @author Daniel Wentsch

$this->setAuthor('Daniel Wentsch');
$this->setDescription('Update localization string (test)');

// Put your updatescript code here!
$this->setLanguageWording('de', 'Telephone number', 'Telefonnummer');
$this->setLanguageWording('de', 'Fax number', 'Faxnummer');


Generate new Drupal 7 Password Hash

If you find yourself locked out of your own Drupal installation and are unlucky enough to not receive any password-restore emails (or your server not being able to send them) you need to set a new password directly in the database. As Drupal stores a salted sha512 hash (and no plain passwords, of course) you need to encrypt your new password before you can store it in your database.

To do this you can either use the Shell script called provided in the scripts folder of any Drupal installation. In case you don’t have access to a shell you can also use the user_hash_password function in PHP:

This could be put in your index.php temporarily after bootstrapping Drupal. After visiting your site a string will be displayed. Replace your admin’s password in the users table in the database with that string and you can now log in with YourNewPassword.

require_once 'includes/';
echo user_hash_password('YourNewPassword'); 

Override Superfish’s Mobile Menu Trigger in Drupal

The Superfish integration for Drupal works nicely for all kinds of menus from Mega Dropdowns down to Mobile. What bothered me with Superfish’s Mobile Menu implementation is that the Button that opens the Mobile Accordion (.sf-accordion-toggle) is always named after the name of the actual menu and normally can’t be overridden.

One possible approach to overcome this is using plain CSS to hide the span and place something different inside the link tag using the content property. I don’t like that idea too much so instead I tried figuring out how to change this with JavaScript. Turned out it’s not possible to simply selecting the DOM element and changing its value because the original value gets re-assigned anytime you resize you browser windows. What does work is overriding the Superfish behavior. I just copied it over from superfish.js form the Superfish Module into my theme’s JS and there I set my desire value, like so: options.plugins.smallscreen.title = '<i class="glyphicon glyphicon-menu-hamburger "/><span>Menü</span>';

Here’s the entire function:

// Override the superfish Behevior to add our own 
// custom Mobile Menu Trigger Title // (options.plugins.smallscreen.title)
(function ($) {
  Drupal.behaviors.superfish = {
    attach: function (context, settings) {
      // Take a look at each list to apply Superfish to.
      $.each(settings.superfish || {}, function(index, options) {
        // Process all Superfish lists.
        $('#superfish-' +, context).once('superfish', function() {
          var list = $(this);
          options.plugins.smallscreen.title = '<i class="glyphicon glyphicon-menu-hamburger "/><span>Menü</span>';
          // Check if we are to apply the Supersubs plug-in to it.
          if (options.plugins || false) {
            if (options.plugins.supersubs || false) {

          // Apply Superfish to the list.

          // Check if we are to apply any other plug-in to it.
          if (options.plugins || false) {
            if (options.plugins.touchscreen || false) {
            if (options.plugins.smallscreen || false) {
            if (options.plugins.automaticwidth || false) {
            if (options.plugins.supposition || false) {
            if (options.plugins.bgiframe || false) {

Let Drupal Editors Pick a Color and use it in Template

I’m currently working on an image slider where each slide needs to have its own background color.

Letting editors choose a color is easy with the Color Field Module. Just install it, throw the Spectrum Color Picker into your libraries folder and add and configure a Color Field where ever it’s needed. You can then simply access the user-entered color as a hex string in your template and use it to your liking (yea, that’s one of the rare times where it’s ok to use inline style, at least in my book).

Convert Hexadecimal Color Values to RGBa

I needed my color to have alpha transparency, however, the color value is only available as a hexadecimal string. Luckily I found this handy snippet to convert hex values to RGB(a), so thanks a lot to mekshq for sharing.

Just put it into your template.php and you’re good to to to use hex2rgba() anywhere in your theme.

/* Convert hexdec color string to rgb(a) string */
function hex2rgba($color, $opacity = false) {

  $default = 'rgb(0,0,0)';

  //Return default if no color provided
          return $default; 

  //Sanitize $color if "#" is provided 
        if ($color[0] == '#' ) {
          $color = substr( $color, 1 );

        //Check if color has 6 or 3 characters and get values
        if (strlen($color) == 6) {
                $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
        } elseif ( strlen( $color ) == 3 ) {
                $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
        } else {
                return $default;

        //Convert hexadec to rgb
        $rgb =  array_map('hexdec', $hex);

        //Check if opacity is set(rgba or rgb)
          if(abs($opacity) > 1)
            $opacity = 1.0;
          $output = 'rgba('.implode(",",$rgb).','.$opacity.')';
        } else {
          $output = 'rgb('.implode(",",$rgb).')';

        //Return rgb(a) color string
        return $output;

Deleting Drupal Fields programmatically implementing hook_update_N()

Say we’d like to get rid of a Drupal Field that has the machine name field_wein_texte and our module that’s supposed to manage this is called kx_deployment. Here’s how the kx_deployment.install needs to look like:

* Implements hook_update_N().
* Managing Field Deletions programmatically
* Note: field_delete_fields() removes fields globally, to detach a field from an entity use field_delete_instance()
function kx_deployment_update_7001() {
  $fields_to_delete = array(
  foreach ($fields_to_delete as $field_name) {
    watchdog('kx_deployment', 'Deleted the :field_name field from all content type instances.', array(':field_name' => $field_name));
// The fields aren't really deleted until the purge function runs, ordinarily
// during cron.  Count the number of fields we need to purge, and add five in
// case a few other miscellaneous fields are in there somehow.
if(isset($fields_to_delete)) {
  field_purge_batch(count($fields_to_delete) + 5);


Drupal: Insert JavaScript for Every Page except Front Page

Just a quick reminder for myself how to simply load an asset only if a certain condition is true.

In template.php we need to implement template_preprocess_page() check our condition and load our script using drupal_add_js():

function MYTHEME_preprocess_page(&$vars) {
  // if we're NOT on the front page load a script from the currently active default theme
  if (!$vars['is_front']) {
    $active_theme = drupal_get_path('theme',$GLOBALS['theme']);

Using Node.js modules in your Drupal Themes

As my frontend development workflow gets more and more dependent on Grunt and node.js there are are issues coming up when Drupal tries to parse .info files from theme directories. I’ve had a hard time working around this by putting Gruntfile.js and package.json in a hidden subdirectory of my theme, but this resulted in a lot of broken Grunt tasks (and it’s basically yet another hack because it simply relies on the fact that Drupal doesn’t scan directories starting with a dot).

Continue reading

Setting up and Using Environments with htaccess

This .htaccess snippet does the following:

  1. Create two environments called staging and development based on the host name
  2. Set up ht authentication only on the stage server (Deny from env=staging)
  3. Rewrite all requests to the main domain ( if we’re not on either the development nor staging environment and the host doesn’t already equal the main domain
AuthName „Staging Server"
AuthType Basic
AuthUserFile /var/sites/mysite/.htpasswd
AuthGroupFile /dev/null
require valid-user

SetEnvIf Host env=staging
SetEnvIf Host env=development

Order Allow,Deny
Allow from all
Deny from env=staging

Satisfy Any

<IfModule mod_rewrite.c>
  RewriteBase /

  RewriteCond %{ENV:env} !development
  RewriteCond %{ENV:env} !staging
  RewriteCond %{HTTP_HOST} !^mysite\.dev$ [NC]
  RewriteCond %{HTTP_HOST} !^www.mysite\.com$ [NC]
  RewriteRule ^(.*)$ [R=301,L]

On github:

Drupal: Keep EXIF orientation and allow manual cropping of images

Wow, this is more troublesome than expected.

Goal: Let users upload images straight from a camera and manually select an area of the image that should be cropped.

Issue: nearly all modern cameras use EXIF information to tell an images orientation. Drupal image actions ignore this information and all images in landscape format resulting in flipped portrait images. Imagecache Actions module provides an action to rotate images based on EXIF data. But: this doesn’t work if the image was resized to the maximum dimensions straight after the upload. And: it doesn’t play nice with most image cropping modules.

I’ve been fighting this issue for some hours now and have something that seems to work for me. It’s not extensively tested yet, though. Here’s what I came up with:


  • ImageMagick instead of GD as Image Toolkit (because GD strips EXIF data)
  • Imagecache Autorotate, part of [Imagecache Actions](Imagecache Autorotate) that provides an Image Action that automatically rotates pictures according to their EXIF orientation
  • EPSA Crop module: EPSA crop was the only cropping module that allowed me to use its after the Autorotate action in my image style preset (I tried at least with manualcrop, imagefield_crop, simplecrop)

In my image style I use the following actions:

  1. Autorotate image based on its EXIF data
  2. EPSA Image Crop, 150×150 (with Aspect Ratio of one, as the resulting image has a square AR)
  3. Scale and Crop, 150×150, scale and crop it even if it wasn’t manually cropped.

Only drawback so far:
EPSA Crop doesn’t show you the cropped image on the thumbnail of the edit page, so users might be confused if their cropping was successful after all.

Originally posted on DrupalAnswers, might be interesting to follow the discussion

Hope this helps others saving some hours of research.

Generate and display preview images for your PDF files with Drupal

When serving PDF files it’s always nice to show a little preview image of the document.

These are the steps I needed to take to get a preview image of the first page of any uploaded PDF document.

  1. Make sure you have ImageMagick available on your server and that the convert executable can be called from PHP (As my hosting company provides a precompiled version of ImageMagick I only needed to enable the extension by adding extension="" to my php.ini)
  2. Install the ImageMagick module for Drupal
  3. Make ImageMagick your default image toolkit and make sure you have set the correct path to ImageMagick’s convert binary on admin/config/media/image-toolkit (for me that is /usr/bin/convert)
  4. Check if ImageMagick works correctly (e.g. Upload an image and check if derivative images are generated without errors)
  5. Install the PDF Preview module for Drupal
  6. Go to admin/config/media/pdfpreview and hit save (change your preview image dimensions if desired, but keep it big, we can later use other presets to display the image). It’s important so save this page, no matter if you changed any setting at all, otherwise the image generation won’t work (see
  7. Choose the PDF Preview formatter in the display settings of a file field that contains your PDF files and choose your desired image preset.
  8. Done!

Update: Accessing preview images from PDF Preview programmatically

After I was happy with the functionality provided by the modules it turned out I needed to access the preview images from my templates in order to show additional information about the file, such as download links and file size and description. Turns out it’s quite easy using _pdfpreview_create_preview(). Just throw your file object as a parameter and you’ll get the desired preview image of that file returned! Here’s a little snippet that iterates all files of a multi-value file field and outputs each field as a list item with the preview image rendered with an image preset (katalog in this case) and shows the file description below (file links are still missing but easy to implement):

<?php if($field_produkt_kataloge): ?>
  <ul class="field-produkt-kataloge">
    <?php foreach($field_produkt_kataloge as $katalog): ?>
        <?php $katalog_preview_url = _pdfpreview_create_preview($katalog);?>
        <?php $katalog_preview_image = theme('image_style', array('style_name' => 'katalog', 'path' => $katalog_preview_url)); ?>
        <?php print $katalog_preview_image; ?>
        <?php print $katalog['description']; ?>
    <?php endforeach; ?>
<?php endif; ?>