How to customize a textarea field? I have created a textarea field using admin ui. It allows users to add Bio to their profile. I want to do 2 things with this field.


Limit the characters to 255.
Use a text format. Note: I do not want to allow users to choose a text format.
With HTML5 on Drupal 7 no JS is necessary if we can add a maxlength attribute to the textarea tag.

I tried to use a hook_form_alter to set this attribute, something like

$form['field_NAME'][LANGUAGE_NONE][0]['#attributes'] = array('maxlength' =&gt; 220);


or

$form['field_NAME'][LANGUAGE_NONE][0]['#maxlength'] = 220;


...and a gazillion variations using dsm($form) for ideas and to check my results. I could easily change the $form['field_name'] values but my textarea failed to acquire the maxlength atttribute.

This worked:

/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 * Add a maxlength attribute to field_NAME.
 */
function MYMODULE_field_widget_text_textarea_form_alter(&amp;$element, &amp;$form_state, $context) {
  if (isset($element['#field_name']) &amp;&amp; ($element['#field_name'] == 'field_NAME')) {
    $element['value']['#attributes'] = array('maxlength' =&gt; 220);
  }
}