11

I need to limit the textarea message of the core module contact form to a certain number of characters.

Here are the facts

  1. The Form API does not allow one to set a maxlength on textarea field types [while plain HTML does]

  2. The Maxlength module , doesn't allow you to actually set a maximum length. It gets its max length from the field's max length, defined on each content type's manage field section

  3. Creating a new form element type using hook_element_info, still doesn't gurantee I can add the #maxlength to the textarea. Besides if I succeed I need to alter again the contact form module to overrride actual message textarea field with mine.

So I can I alter it plain and straightforward?

What is the best idea to alter all textarea fields in the website?

0

3 Answers 3

6

The Form API does not allow to set a maxlength on textarea field types [while plain HTML does]

That's not strictly true....HTML5 introduced a maxlength property for textareas, previous versions do not have it (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea).

The default templates that come with Drupal 7 all use XHTML, so the lack of explicit support for HTML5 makes perfect sense.

As long as your doctype is HTML5, this will probably work:

$form['element'] = array(
  '#type' => 'textarea',
  '#attributes' => array('maxlength' => 200),
);
1
  • Clive I actually found a working solution, I posted it below. Thanks for your answer. Commented Oct 24, 2013 at 12:29
6

You can use Maxlength module like this, put both #maxlength and #maxlength_js properties on the elements you want to control.

$form['comments'] = array(
  '#type' => 'textarea',
  '#title' => t('Comments'),
  '#maxlength_js' => TRUE,
  '#maxlength' => 1000,
);
4

Firstly off I defined a setting form, then made a hook form alter:

function contact_form_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'contact_site_form') {
    $maximum_limit = (int) variable_get('contact_form_maxlength', 500);
    if($maximum_limit && is_numeric($maximum_limit)) {
    $form['message']['#title'] = $form['message']['#title'] . t(' (maximum @max characters)', array( '@max' => $maximum_limit));
    $form['message']['#maxlength'] = $maximum_limit ;
    }
  }
}

This seems to be working fine.

2
  • Just as an aside, you could implement hook_form_FORM_ID_alter and save the form ID check, ie: contact_form_form_contact_site_form_alter. Bit of a mouthful as a function name, admittedly. Commented Oct 24, 2013 at 13:03
  • That is a great idea. I don't have this habit :-) Commented Oct 24, 2013 at 13:33

Your Answer

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

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