Set a custom CSS class to an image in Drupal 7

Drupal I’m working for a customer to create a Bootstrap 3 theme from scratch, since I’ve to create a kind of portfolio-like page with some thumbnails I needed to apply the Bootstrap’s CSS class img-thumbnail to all the images.

It took some time but the action is possible and take few steps, it assume that you are using a custom image style type to display your image(s):

1. In your template.php file you need to define a new override function like this:

function fancythemename_preprocess_image(&$variables) {
 if (isset($variables['style_name'])) {
  if ($variables['style_name'] == 'fancystylename')
   $variables['attributes']['class'][] = 'img-thumbnail'; //bootstrap class
 }
}

That is,
happy coding!

Drupal 7: how to hide unwanted tabs

DrupalAssuming you want to hide some tabs from a specific page, content type, user role, specific URLs or other discriminating criteria, you need to work on the $variables variable and unset the unneeded tabs.

The following snippet will remove “subscriptions” and “favorites” tabs to all the non “editor” users:

if($variables['user']->uid > 1 && !in_array('editor', $variables['user']->roles) && !in_array('administrator', $variables['user']->roles)) {
 $to_be_removed = array('user/%/subscriptions', 'user/%/favorites');
 foreach ($variables['tabs'] as $group_key => $tab_group) {
  if (is_array($tab_group)) {
   foreach ($tab_group as $key => $tab) {
    if (isset($tab['#link']['path']) && in_array($tab['#link']['path'], $to_be_removed)){
     unset($variables['tabs'][$group_key][$key]);
    }
   }
  }
 }
}

Enjoy!

Drupal 7: Add a class to the body

Drupal Today I had to add a class to the body so know if I was logged in as “administrator” like role, it needed to have the permission to modify any content of the type MYTYPE.

To add a class to the body you have to work on the template_preprocess_html for your theme, like the snippet below.

function MYTHEME_preprocess_html(&$vars) {
  if(user_access("edit any MYTYPE content")){
    $vars['classes_array'][] = "MYCLASS";
  }
}

The user_access() will check if the current user (if there isn’t one specified) has the selected permission, the permission is the one you can see from the permission administration page, if you are using Drupal in another language then refer to the base English interface to know what to write there.

Enjoy!

Drupal 7: Manually update jQuery version

Drupal Today for a customer I had to use a special plugin for jQuery that needs a jQuery version equal or major than 1.6.1.

As you know Drupal 7 is shipped with jQuery 1.4.4 and so is not ready for the plugin I need to use, there is a plugin that update jQuery and jQuery UI but where is the fun?

The procedure is pretty quick:

  • Download the jQuery version you need from from the official source.
  • Place the jQuery version you downloaded in your theme js’s folder (like MYTHEME/js/).
  • Create/Modify your theme’s template.php file as described below.

That is.

Now for the template.php, you need to use the hook_js_alter to replace the native jQuery:

function MYTHEME_js_alter(&$javascript) {
  //We define the path of our new jquery core file
  //assuming we are using the minified version 1.8.3
  $jquery_path = drupal_get_path('theme','MYTHEME') . '/js/jquery-1.8.3.min.js';

  //We duplicate the important information from the Drupal one
  $javascript[$jquery_path] = $javascript['misc/jquery.js'];
  //..and we update the information that we care about
  $javascript[$jquery_path]['version'] = '1.8.3';
  $javascript[$jquery_path]['data'] = $jquery_path;

  //Then we remove the Drupal core version
  unset($javascript['misc/jquery.js']);
}

After we clear the cache we will have the new jQuery version.

Keep in mind that changing the jQuery version may create some incompatibility issues with the other Drupal core scripts.

Enjoy!

Drupal SA-CORE-2012-003 quick fix

Drupal Recently Drupal released the new version (7.16) to fix a security issue that would allow an attacker to reinstall an existing Drupal site with an external database server and then execute custom PHP code, more information available here: http://drupal.org/node/1815912.

There are many way to prevent this instead of updating a Drupal installation (always recommended), probably the quickest is to deny access to the interested file with few lines for the .htaccess file:


<Files install.php>
  deny from all
  ErrorDocument 403 "Access denied."
</Files>

Enjoy!

Drupal 7: how to create a form within a module

Drupal If you develop modules and you need to create a form in one of your page, there is a nice Drupal function that can render an array into a pretty HTML form: drupal_get_form().

This handy function is usually needed in a menu callback as it does not require an existing form.

You can use it like this:

/**
 * Implements hook_menu()
 */
function mymodule_menu() {
 $items['mymodule'] = array(
  'title' => 'My title', //The name of the menu that will be displayed
  'page callback' => 'mymodule_page_callback', //The name of the function that will output a page
 );
 return $items;
}

function mymodule_page_callback() {
 //The argument is the name of the function with the form details
 return drupal_get_form('mymodule_form');
}

function mymodule_form($form, &$form_state) {
 $form = array (
  //The action attribute of the HTML form tag
  '#action' => '#', 
  //We define a simple text field for the "name"
  'name' => array ( 
   '#type' => 'textfield',
   //The label that will be placed with the field
   '#title' => t('My pretty name'),
   //The description will be placed right below the field
   '#description' => t('My descrition'),
   //If true the system will perform a simple check on submit so that it is never empty
   '#required' => TRUE,
  ),
  //We define a simple submit button
  'submit' => array ( 
   '#type' => 'submit',
   '#value' => t('My submit'),
  ),
 );
 
 return $form;
}

After you have defined the form, you can implement 2 extra functions that will handle the validation (_validate) and the processing (_submit) of the form values.

function mymodule_form_validate($form, &$form_state){
 // My validation parameters
 if(strlen($form_state['values']['name']) > 10) {
  form_set_error('', t('Hey, your name is too long!'));
 }
}

function mymodule_form_submit($form, &$form_state) {
 //My success processing
 drupal_set_message(t('Yay, your name is fine!'));
}

And that is, pretty simple uh?

2013 10 10 Edit: Updated with the syntax highlighter!

SSH/Shell update Drupal from a minor version to another

Drupal Hello everyone,
last day I had to update Drupal 7.10 to the most recent at the moment (7.12), I never did something like that so I was like “here we go, 1 work day that will go burned! :D”, but thanks to the Drupal community I was able to update the installation.

Since isn’t very easy at first (reading UPGRADE.txt was not helpful unfortunately), therefore here a quick list of the steps:

  1. Put your site into maintenance mode or close accesses from the outside.
  2. First of all, backup your installation folder (usually a rsync -av startfolder destinationfolder, or a cp -a startfolder destinationfolder will do the job just fine)
  3. Then you have to backup your database (you can do it all in one step using screen, but I bet that if you are reading this and you are experienced you already know that), depending if you are running MySQL or PostgreSQLthe instructions changes, but I think could be sum up as follows:
    • MySQL: mysqldump -uUser -pPassword -hHost dbname > dumpname.sql
    • PostgreSQL: pg_dump databasename > dumpname.sql

    If you use PostgreSQL you need to remember that the operations have to be done with the correct user. Refer to the documentation for further details.

  4. After you have done the backups, reach your site root folder and create a folder to hold the new Drupal version, something like mkdir upgrade, then enter inside it with cd upgrade.
  5. Download the archive with wget http://ftp.drupal.org/files/projects/drupal-7.12.tar.gz.
  6. Open the archive with tar -xzvpf drupal-7.12.tar.gz.
  7. Then enter the newly created directory like we did before, cd drupal-7.12.
  8. At this point we have all that we need, this step is the actual upgrade, we have to move some files in the root directory, assuming you followed this steps, the command you need is the following:
    rsync -av CHANGELOG.txt COPYRIGHT.txt cron.php includes index.php INSTALL.mysql.txt INSTALL.pgsql.txt install.php INSTALL.txt LICENSE.txt MAINTAINERS.txt misc modules profiles scripts themes update.php UPGRADE.txt xmlrpc.php ../../
  9. After you have done that, should be an instant action, open your browser and go to your website URL and add a /update.php at the end, you should have http://www.myawesomedrupalsite.com/update.php.
  10. Follow the instruction on-screen to complete the update process on the database, don’t change anything from the dropdowns.
  11. Once the update is complete you may remove the directory we created to download and extract drupal.

Is not very short but is all you need to do.

Enjoy!