Advertising sustains the DA. Ads are hidden for members. Join today

Code Usage

Last updated on
30 August 2021

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

This documentation needs review. See "Help improve this page" in the sidebar.

Maxlength creates a new Form Property: #maxlength_js which, in conjunction with #maxlength, will enforce (via JavaScript) the maxlength of a textfield, a textarea, or a text_format and will show the number of characters left.

Whether when creating a form or when altering one, put both #maxlength and #maxlength_js properties on the elements you want to control.

#maxlength

Description: The maximum amount of characters to accept as input.

Values: A positive number.

#maxlength_js

Used by: textfield, textarea, text_format

Description: Indicates whether or not the field should have a reverse character counter.

Values: TRUE or FALSE

Form API Example

 $form['description'] = array(
 '#required' => '1',
 '#description' => t('Max. 500 Characters'),
 '#type' => 'textarea',
 '#maxlength' => 500,
 '#maxlength_js' => TRUE,
 '#attributes' =>array(
 'maxlength_js_label' => '@remaining characters left.',
 ),
 '#title' => t('Detailed Description (required)'),
 );

Extras:

For the text of a link field:

/**
 * Implements hook_field_widget_form_alter().
 */
function MODULE_NAME_field_widget_form_alter(&$element, Drupal\Core\Form\FormStateInterface $form_state, $context) {
 $items = $context['items'];
 $field = $items->getName();
 if ($field == "field_NAME") {
 if (key_exists('form_id', $form_state->getBuildInfo())) {
 $build_info = $form_state->getBuildInfo();
 if ($build_info['form_id'] == 'FORM_ID' || $build_info['form_id'] == 'FORM_ID_EDIT') {
 $element['title']['#maxlength_js'] = TRUE;
 $element['title']['value']['#maxlength_js'] = TRUE;
 $maxlength_js = 500;
 $element['title']['value']['#attributes']['maxlength'] = $maxlength_js;
 $element['title']['#attributes']['maxlength'] = $maxlength_js;
 $maxlength_js_label = 'Contenido limitado a @limit caracteres, quedan: <strong>@remaining</strong>';
 $element['title']['#attributes']['maxlength_js_label'][] = $maxlength_js_label;
 $element['title']['value']['#attributes']['maxlength_js_label'][] = $maxlength_js_label;
 }
 }
 }
}

Help improve this page

Page status: Needs review

You can: