Tag Archives: snippet

Custom 404 page template in Drupal

A simple snippet to define a custom 404 and 403 theme suggestion in Drupal:

function YOURTHEME_preprocess_page(&$vars) {
  $header = drupal_get_http_header("status");
  if($header == "404 Not Found") {
    $vars['theme_hook_suggestions'][] = 'page__404';
  }
  if($header == "403 Forbidden") {
    $vars['theme_hook_suggestions'][] = 'page__403';
  }
}

The template file should be named page--404.tpl.php and clear the cache and this should work.

Source: https://www.drupal.org/node/15366#comment-7218780

Adding users

In a previous post I’ve showed some code to add nodes to Drupal, in this blog I will show that the same can be done with user objects.


$roles = array(
   5 => 'visitor'
);

$fields = array(
    'name' => $username,
    'mail' => $email,
    'pass' => $password,
    'status' => 1,
    'init' => 'email address',
    'roles' => $roles
);
  
//the first parameter is left blank so a new user is created
$account = user_save('', $fields);

// $account will contain the new created user object

The fields are rather simple and easy to understand what they do:

  • name; loginname of the user
  • mail; email address
  • pass; plaintext password, will be hashed on save
  • status; 1 for an active user and 0 for an blocked user
  • roles; an array with the roles to assign to the user. The number and name is different per Drupal installation

So it is rather simple to add an user in Drupal, as it should be 🙂