Okay, so I want to add a maxlength to a textarea, however, form api doesn't appear to have a way to do this. It only has #maxlength for textfields. I have a form for my users to enter data, my php breaks it up and sends the information into a table in my database...problem is, if a user enters too much data at once, it can completely slow down my entire site and sometimes almost make it so slow it basically crashes. I need to limit how much my users enter in at once. Ideally I want to add a maxlength and some how communicate to the user that he/she has gone over the limit...I was thinking about a counter, but not sure how I'd do that with form api. Anyways, for now I'm just looking to add a limit. How can I do this?

Thanks,
Collin

Comments

Anonymous’s picture

removed

mcurry’s picture

Definitely do the validation hook stuff. For those who want more interactive feedback for the user, this trick works for javascript-enabled browsers (in addition to the validation code shown elsewhere in the comments.)

'#attributes'=>array('onKeyPress'=>"return(this.value.length<$max_length);")

(Add that to your form field definition, as in the example below)

  $max_length = 50; // 50 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);),    
  );

-------------
Michael Curry
Amadorable - RubyPowered - RoadCarvin'

ardas’s picture

Thanks for directing me to the solution. I found the big problem in this script - all navigation buttons stop working when you reach maximum. You can't even refresh page using F5 button.

Here is the revised solution. Set onKeyPress event for your textarea like this:

    '#attributes' => array('onKeyPress' => "return textareaMaxLength(this, event, $sms_max_len);"),

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);
}

This was tested in FireFox, Opera and IE 6.
----------------
Regards,
Dmitry Kresin, ARDAS group (ARDAS group)

aries’s picture

Why don't you try to implement this? http://test2.danieleastwell.co.uk/test/textarea-max/textarea-max.html
--
Fehér János aka Aries
http://aries.mindworks.hu

johnhanley’s picture

... thanks for sharing.

DriesK’s picture

You can use _validate, in which you can count characters, words, ... For example, if your form looks like this:

$form['text'] = array(
  '#type' => 'textarea',
  '#title' => t('Text'),
  '#description' => t('No more than 200 words please!'),
);
return drupal_get_form('myform', $form);

you could do:

function myform_validate($form_id, $edit) {
  if (str_word_count($edit['text']) > 200) {
    form_set_error('text', t('Woops! Too many words'));
  }
}

or for chars:

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

Validation isn't that solution clients want to see. May be because it is slow - you need to refresh your page.
----------------
Regards,
Dmitry Kresin, ARDAS group (ARDAS group)

christefano’s picture

Have you tried the Maxlength module?



Christefano  
Founder, CEO
Large Robot
954-247-4786
http://www.largerobot.com
agalitsyn’s picture

You can do it with JS. Just preventing user to add more characters on keyboard, and show him gray background (like disabled area)

In your module:

define('EXAMPLE_SITE_COMMENT_CHARACTERS_MAX', 1500);

/**
 * Implements hook_init().
 */
function example_site_init() {
  // Add js constant.
  drupal_add_js(
    array(
      'exampleSite' => array(
        'commentCharactersMax' => variable_get(
          'exapmle_site_comment_max_length',
          EXAMPLE_SITE_COMMENT_CHARACTERS_MAX
        )
      ),
    ),
    'setting'
  );
}

In JS (Don't pay attention to php tagss, added for highlihting on d.org)

ExampleSite = {
  getCommentCharsMax: function() {
    return Drupal.settings.exampleSite.commentCharactersMax;
  },
}

Drupal.behaviors.exampleSite = function(context) {
   textareaMaxLength();
}

// Presentation textarea length.
function textareaMaxLength() {
  var selectors = [
    'div.block-info.block-top-info div.txt-block',    
  ];
  var notselectors = [
    '.textarea-field-processed'
  ];

  $(selectors.join(', ')).not(notselectors.join(', ')).each(function() {
    var $this = $(this);
    $this.addClass('textarea-field-processed');
    var textarea = $('textarea', $this);
    var chars = $('div.label span i', $this);

    var maxChars = window.ExampleSite ? ExampleSite.getCommentCharsMax() : 1500;

    textarea.attr('maxlength', maxChars);
    textarea.bind('keyup keydown', function(){
      if($(this).val().length > maxChars){
	$(this).val($(this).val().substr(0, maxChars));
      }
      chars.text(maxChars - $(this).val().length);
      // Show grey background when textarea is more than 500 characters.
      if ($(this).val().length > (maxChars - 1)) {
        $(this).css('background-color', '#CCC');
      }
      else {
        $(this).css('background-color', 'white');
      }
    });
  });
}
FriOne’s picture

OMG, why not this?

'textarea' => array(
  '#type' => 'textarea',
  '#attributes' => array('maxlength' => 1000),
),
RobertoGA’s picture

Works like a charm, thanks men ;)

jtege’s picture

Using the devel module [for example, using the dpm command in form_alter hook - "dpm($form)"], drill down into the $form array and you'll see where to adjust the value to set 'maxlength'.
"$form['my_textarea_form_field']['und'][0]['value']['#attributes']['maxlength'] = 1000;" worked for me. You can adjust this value in a form_alter hook, or anywhere else you have access to the form array before it is sent to the theme engine...I think. For a counter, I would be using an ajax callback. But I know there are many ways to skin drupal cats.

sneha_surve’s picture

Works for me! thanks :D

norman.lol’s picture

Download and enable https://www.drupal.org/project/maxlength, then you simply can use #maxlength_js:

$form['some_textfield'] = array(
  '#type' => 'textarea',
  '#maxlength_js' => TRUE,
  '#maxlength' => 150,
);
JohnnyW’s picture

Brillant! Thank you for that suggestion -- saved me some troubles.

'#maxlength_js' => TRUE,
  '#maxlength' => 150,

Worked out perfectly! Thanks again!!

feelcreative’s picture

If using EntityForms, you could use plain old javascript in a "static" field right after the textareas are defined:

<script>
    document.getElementsByTagName("textarea")[0].setAttribute("maxlength", "500");
</script>
sprite’s picture

Why are you necroposting to a decade on thread?

He's building a Drupal website ....

How exactly is he going to inject the javascript in the context of a DRupal website building without the use of yet another module?

spritefully yours
Technical assistance provided to the Drupal community on my own time ...
Thank yous appreciated ...

feelcreative’s picture

Right oh mate, relax.

Comment above relates specifically EntityForms. Instead of adding another module, use entityform's static field to inject some JS.