Mukesh
Mukesh

Reputation: 7778

How do I limit number of characters in the admin form in magento

I have following code in my Form.php

$fieldset->addField('desc', 'textarea', array(
          'label'     => Mage::helper('module')->__('Description'),
          'required'  => true,       
          'name'      => 'desc',
      ));

How to restrict the number of characters in this text area?

Upvotes: 3

Views: 7889

Answers (1)

Marius
Marius

Reputation: 15216

In theory you should be able to do that by adding to the textarea a maxlength attribute.
So you should end up with something like this:

<textarea maxlength="50"></textarea>

But Magento does not allow the maxlength attribute.
If you take a look at the Varien_Data_Form_Element_Textarea class (the one responsable for rendering textareas) you will see this method.

public function getHtmlAttributes()
{
    return array('title', 'class', 'style', 'onclick', 'onchange', 'rows', 'cols', 'readonly', 'disabled', 'onkeyup', 'tabindex');
}  

Those are the only ones that you can specify when you create the element.

First option would be to extend this class and add the maxlength among the allowed attributes, then your column could look like this:

$fieldset->addField('desc', 'textarea', array(
      'label'     => Mage::helper('module')->__('Description'),
      'required'  => true,       
      'name'      => 'desc',
      'maxlength' => 50
));

The second option is to add it via some javascript.

   $fieldset->addField('desc', 'textarea', array(
      'label'     => Mage::helper('module')->__('Description'),
      'required'  => true,       
      'name'      => 'desc',
      'after_element_html' => '<script type="text/javascript">Event.observe(window, "load", function() {$("id_of_textarea_here").setAttribute("maxlength", 50)})</script>'
  ));

A third option would be to insert instead of the javascript above some code that limits the length of the text.
You can find an example here.

Final Note:
the content from after_element_html will be displayed in the form right after the element. So you can basically put anything there.

Upvotes: 12

Related Questions