Text Size
Sunday, May 20, 2012
Get a look down
Code snippets
Code snippets

Code snippets (12)

Sometimes we need to generate a CSV file dynamically, and launch it as downloadable file, it works fine in Firefox, Opera, Chrome and other guru browsers, but when we talk about Internet Explorer, maybe we need to hack the code.

By googling a little, i found an easy solution, so in php, we can do it like this :

 

1
2
3
4
5
6
7
8
9
<?php
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"exportevent.csv\";" );
header("Content-Transfer-Encoding: binary"); 
?>

You can use this little snippet to scroll to the top of the page using javascript (in case you don't wan't to use html anchors)

1
2
3
<!-- The click on this link will take you to the top of the page -->
<!-- Place this link on the bottom of the page -->
<a href="#" onclick="window.scroll(); return false">Scroll to the top</a>

Here's a little snippet that allow's us to remove any non alphanumeric characters from strings. It would be very usefull when a developper need to format a given string from a registration form for example.

1
2
3
4
5
6
7
8
9
10
<?php
// Our string
$words = "Hello! My Name Is Nabil SADKI 007!!!";
 
// Formatted string
$formatted_words = preg_replace("[^A-Za-z0-9]", "", $words ); // This will print : HelloMyNameIsNabilSADKI007
 
// Get only alpha
$formatted_words = preg_replace("[^A-Za-z]", "", $words ); // This will print : HelloMyNameIsNabilSADKI
?>
Here's how you can get the first N elements of an array, it's so simple with the use of array_slice :
1
2
3
4
5
6
7
8
9
10
<?php
// Array
$myArray = array("bird", "dog", "cat", "horse", "lizard");
 
// Get the 2 first elements
$output = array_slice($myArray, 0, 2);
 
// Result
// This will give an array with elements : "bird", "dog"
?>

All Drupal's based websites come's with the same administration path /admin, so if someone know that your site is built with Drupal, he can easily access the admin access page. This path can be changed easily with this little configuration. Just place this code snippet in your settings.php file, and change the admin word with the one you wan't :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Change mywebpanel with the word you need
// Admin page can be seen with the new link : http://www.mywebsite.com/mywebpanel
function custom_url_rewrite($op, $result, $path) {
 
  if ($op == 'alias') {
    if (preg_match('|^admin(/{0,1}.*)|', $path, $matches)) {
      return 'config'. $matches[1];
    }
  }
 
  if ($op == 'source') {
    if (preg_match('|^mywebpanel(/{0,1}.*)|', $path, $matches)) {
      return 'admin'. $matches[1];
    }
  }
 
  return $result;
 
}

You can check by this little snippet if the actual user visiting your website is logged in or not. This snippet can be used anywhere (modules, themes, blocks..)

1
2
3
4
5
6
7
8
9
<?php
  global $user;
  if ($user->uid) {
    // User is logged in. Do something.
  }
  else {
    // User in anonymous. Do something.
  }
?>

Here's how you can make a string translatable in your javascript files loaded in Drupal.

1
2
3
4
5
6
7
8
// This little code will append a <div> to the body.
// The <div> contains a translatable string "Hello world!"
// You can translate this string easily in the Back office
// of your website by browsing this url : 
// http://you.website.here/admin/build/translate/search
// and search for Hello world!
// PS : it's a case sensitive input
$('<div>'+Drupal.t("Hello world!")+'</div>').appendTo('body');

You can use imagecache directly in your module, invoke a preset, and apply it on an uploaded image with this code snippet :

1
2
3
4
5
6
7
8
9
10
// $preset: the name of your preset
// $image['filepath']: the path to your file. E.g: sites/default/files/my_picture.jpg
// $alt: the alt of your <img> tag
// $title: the title of your <img> tag
// $attributes: your can add attributes to the <img> tag. E.g: $attributes = array('class' => 'mypic')
//          will add a class 'mypic' to your image.
print theme('imagecache', $preset, $image['filepath'], $alt, $title,  $attributes); 
 
// E.g:
print theme('imagecache', 'my_custom_thumb_preset', 'sites/deafult/files/my_picture.jpg', t('My picture alt'), t('My picture title')); 

You can override the default radios theme by inserting this little code in your template.php file. You can find the default theme function in form.inc in the core folder : includes.

PS: this code is applicable on all form elements, just copy/paste the initial theme function from form.inc (the initial theme function name for our example is theme_radios() ) into your template.php, and rename the function E.g : theme_radios() => your_theme_name_radios()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function etinker_radios($element) {
  $class = 'form-radios';
  if (isset($element['#attributes']['class'])) {
    $class .= ' ' . $element['#attributes']['class'];
  }
  $element['#children'] = (!empty($element['#children']) ? $element['#children'] : '');
  if ($element['#title'] || $element['#description']) {
    unset($element['#id']);
    return theme('form_element', $element, $element['#children']);
  }
  else {
    return $element['#children'];
  }
}

With this little code, you can assign many roles to a specified user :

1
2
3
4
5
6
7
8
9
10
// Here's an example of how to assign two roles to a user
$usr = user_load($uid); // $uid is the user ID
$roles = array(
	'uid' => $uid,
	'roles' => array(
		10 => 'Supervisor', // 10 is the role ID
		17 => 'Author'
		)
	);
user_save($usr, $roles);
Usefull tricks