Tuesday, April 24, 2018 04:35 am EDT

Preserving Line Breaks Using Plain Text Processing for Drupal 7

Bri's picture

Have you ever wanted to use the plain text option under the "Text processing" selection for a textarea control on a form so that your users don't see the options that they get when you choose "Filtered text?"

Filtered text can be great in some cases. It gives the user the ability to choose the input format, such as filtered HTML, Full HTML, WYSIWYG, or any others you may have defined. However, chances are that if you are allowing for user submitted content, this only confused people, and for simple content types, plain text is probably sufficient. In my experience, the one thing I miss when going to plain text is the ability to preserve line breaks. Here is a small routine you can use and adapt in your theme's template.php file to preserve line breaks in textarea controls.

function [MY_THEME]_preprocess_field(&$variables, $hook) {
  if(($variables['element']['#field_type'] == 'text_long' || $variables['element']['#field_type'] == 'text_with_summary') && $variables['element']['#items'][0]['format'] == null) {
    $variables['items'][0]['#markup'] = nl2br($variables['items'][0]['#markup']);
  }
}