Cleaning up the save function

This screencast present little new information about writing Drupal modules, but shows some cleanup work for the Word list configuration page – allowing it to take care of unexpected data.
Some Drupal specific topics included in this screencast:

  • Using the t() function with replacements
  • Using the Drupal equivalent of strlen (and other str functions)
  • Seeing Coder react on bad code
  • Discussion on where to add cleanup logic

code changes in wordlist.module

function wordlist_save_list(array $words) {
// Check if the list of words contain any empty strings, and remove them.
$removed = 0;
foreach ($words as $key => $word) {
if (drupal_strlen($word) == 0) {
unset($words[$key]);
$removed++;
}
}

// If any strings were removed, notify the user.
if ($removed > 0) {
drupal_set_message(t(
'Removed @number empty words.',
array('@number' => $removed))
);
}

// Store the words in the variables table.
variable_set('wordlist_words', $words);
}