Max length does not appear on media library upload form

Created on 25 September 2023, 9 months ago
Updated 1 February 2024, 5 months ago

Problem/Motivation

I have created custom field in media where user can add up to 250 character and made use of maxLength. When I go to /media/add/image, it all looks good. I can see the character limit text, however when I add image using wysiwyg ckeditor field and I do not see that.

I tried adding form element values/attributes as well using MODULE_NAME_field_widget_form_alter described in this documentation ( https://www.drupal.org/docs/contributed-modules/maxlength/code-usage β†’ ) and I still so no change.

/**
 * Implements hook_field_widget_form_alter().
 */
function MY_MODULE_field_widget_form_alter(&$element, Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $items = $context['items'];
  $field = $items->getName();

  if ($field == "field_media_caption") {
    if (key_exists('form_id', $form_state->getBuildInfo())) {
      $build_info = $form_state->getBuildInfo();
      if ($build_info['form_id'] == 'media_library_add_form_upload') {
        $element['#maxlength_js'] = TRUE;
        $element['value']['#maxlength_js'] = TRUE;

        $maxlength_js = 500;
        $element['value']['#attributes']['maxlength'] = $maxlength_js;
        $element['#attributes']['maxlength'] = $maxlength_js;

        $maxlength_js_label = 'Contenido limitado a @limit caracteres, quedan: <strong>@remaining</strong>';
        $element['#attributes']['maxlength_js_label'][] = $maxlength_js_label;
        $element['value']['#attributes']['maxlength_js_label'][] = $maxlength_js_label;
      }
    }
  }
}

Surely, I'm not the first one to experience this. Can someone guide me if there is anything that I have missed?

πŸ’¬ Support request
Status

Needs review

Version

2.1

Component

Documentation

Created by

πŸ‡¬πŸ‡§United Kingdom drs2034

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @drs2034
  • πŸ‡©πŸ‡ͺGermany macdev_drupal Wiesbaden

    Got it working for a menu link field that way.

          $form['title']['widget'][0]['value']['#maxlength'] = 25;
          $form['title']['widget'][0]['value']['#attributes']['data-maxlength'] = 25;
          $form['title']['widget'][0]['value']['#maxlength_js'] = TRUE;

    Guess you just need to add that 'data-maxlength' to your example above.
    For my case it needed to be inside of $element['widget'][0]['value'] to get it working.
    The documentation says it different.

  • Status changed to Needs review 5 months ago
  • πŸ‡ΊπŸ‡ΈUnited States cedewey Denver, CO

    Thanks for sharing your solution macdev_drupal.

    drs2034, does that suggestion work for your situation?

    If so, we would appreciate you updating the documentation β†’ with your findings. We'll be sure to credit you on this issue if you do. Thanks!

Production build 0.69.0 2024