1

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.

  1. Limit the characters to 255.
  2. Use a text format. Note: I do not want to allow users to choose a text format.
8
  • Does this field have another use? Can admins do more with the field than standard users? If this is your only use, use a textfield instead of a text area. It is exactly what you want.
    – Quint
    Apr 14, 2017 at 15:28
  • @Quint This textarea field will allow users to write their introduction which will be visible on their profile. I want to enable text format on this field so that input filters can be used. For example :) will be converted to a smiley, url will be converted to a link and so on, but I do not want to allow users to choose a text format from a dropdown. Textfield is totally different thing. It has character limit, but it is just a one line field. Hope now you understand. Let me know.
    – Umair
    Apr 14, 2017 at 17:42
  • Character limit is also important because without it, the user will be able to write long intro, which will make it look weird on user profile.
    – Umair
    Apr 14, 2017 at 17:44
  • 1
    I'm always amazed at the truth of the statement "There's a module for that". It looks like someone else had the same need and created drupal.org/project/maxlength. It validates on client side as well as server side.
    – Quint
    Apr 14, 2017 at 19:53
  • 1
    Limit the characters to 255 -with jquery validation. Hide dropdown from user
    – developer
    Apr 17, 2017 at 5:08

5 Answers 5

4

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' => 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(&$element, &$form_state, $context) {
  if (isset($element['#field_name']) && ($element['#field_name'] == 'field_NAME')) {
    $element['value']['#attributes'] = array('maxlength' => 220);
  }
}
2

For anyone who lands here like I did looking for a way to set maxlength in a Drupal 8 textarea, this worked for me using form_alter:

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

Here is an example using a custom module:

function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    $node = $form_state->getFormObject()->getEntity(); //gets the node
    if ($node->getType() == 'mynode') { //check that it is the node where I want this
        $form['field_NAME']['widget'][0]['value']['#maxlength'] = 220; 
    }
}
2
  • Where to put this thing?
    – Umair
    Apr 30, 2020 at 10:03
  • You can put it in your .theme or custom module using the form_alter hook. In my case I put it in my custom module - see my edit above
    – Peter E
    May 2, 2020 at 11:04
1

There are two modules which can do what you are wanting:

  1. Better formats can hide the filter per role.
  2. Field validation can add additional validation to the field.
4
  • Better formats hides the text format, but how I can assign a text format to a textarea field. The field settings has 2 options. 1. Plaint text 2. Allow user to select a text format.
    – Umair
    Apr 17, 2017 at 10:39
  • If you look at Home » Administration » Configuration » Content authoring, it says that the first format in the list will be the default. Configure your text field to allow the user to select the format and put your desired format at the top of the list. BF will hide the formatting options and your field will get the default.
    – Quint
    Apr 17, 2017 at 14:35
  • You need to edit the field. The field can be configured as "plain text" or as rich text. If it is rich text you can choose the default filter.
    – nvahalik
    Apr 17, 2017 at 14:41
  • @quint If I understood correctly, this will make the, default text format, default for the whole site?
    – Umair
    Apr 18, 2017 at 11:54
1

We can limit the character count to 255 with jQuery validation

  $max_length = 500; // 500 chars max (should pull this from a config var)
  $form['my_textarea'] = array(
    '#type' => 'textarea',
    '#title' => t('Body'),
    '#default_value' => $node->body,
    '#required' => TRUE,
    '#description' => t('The main body text of your entry.  Please note that this is limited to %limit characters or less.', array('%limit'=>$max_length)),
    // this is the item to be added - limit length while typing
    '#attributes'=>array('onKeyPress'=>"return(this.value.length<$max_length);),    
  );

Create a JS file and add it using drupal_add_js:

  drupal_add_js(drupal_get_path('module', 'mymodule'). '/myfile.js');

Inside myfile.js define the following function:

function textareaMaxLength(field, evt, limit) {
  var evt = (evt) ? evt : event;
  var charCode =
    (typeof evt.which != "undefined") ? evt.which :
   ((typeof evt.keyCode != "undefined") ? evt.keyCode : 0);

  if (!(charCode >= 13 && charCode <= 126)) {
    return true;
  }

  return (field.value.length < limit);
}

php validation

function myform_validate($form_id, $edit) {
  if (strlen($edit['text']) > 200) {
    form_set_error('text', t('Your text contains more than 200 characters'));
  }
}

Reference: https://www.drupal.org/node/80122

1
  • 1
    This only handles things on the client side. A bad actor could easily override this.
    – nvahalik
    Apr 17, 2017 at 14:45
0

If you are using Drupal 8, you could put this together pretty fast with:

CKEditor Wordcount has the bonus of not counting HTML tags as characters which works well in the context of a WYSIWYG. I suppose you could add the Field Validation module in here as well, but for this use case, Field Validation would also have to ignore incoming HTML tags when counting characters so that the validations match up.

Better Formats will let you select, per field with text formatting on it, what roles should have access to which filters. If you only select 1 filter, they will not see a filter format drop down at all.

1
  • I am using Drupal 7
    – Umair
    Apr 16, 2017 at 10:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.