Skip to content

Instantly share code, notes, and snippets.

@somatonic
Created December 10, 2012 20:00
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save somatonic/4252958 to your computer and use it in GitHub Desktop.
TextAreaCounter concept module
<?php
// start module to textarea counter
class TextAreaCounter extends WireData implements Module {
//const default_maxlength = 255;
/**
* getModuleInfo is a module required by all modules to tell ProcessWire about them
*
* @return array
*
*/
public static function getModuleInfo() {
return array(
'title' => 'Textarea Counter',
'version' => 1,
'summary' => 'Proof of concept. Counts chars in a textarea',
'href' => '',
'singular' => true,
'autoload' => true
);
}
public function init() {
$this->addHookAfter('InputfieldTextarea::getConfigInputfields', $this, 'hookAddConfig');
$this->addHookBefore('InputfieldTextarea::render', $this, 'renderBeforeTextarea');
$this->addHookAfter('InputfieldTextarea::render', $this, 'renderTextarea');
}
public function hookAddConfig(HookEvent $event) {
// not tinymce fields
if($event->object == "InputfieldTinyMCE") return;
// get inputfields from getConfigInputfields
$inputfields = $event->return;
// add maxlength setting
$f = $this->modules->get("InputfieldInteger");
$f->label = $this->_("Max length");
$f->attr('name','maxchars');
$value = $this->fields->get($event->object->name)->maxchars;
$f->attr('value', $value ? $value : '');
$inputfields->append($f);
}
public function renderBeforeTextarea(HookEvent $event){
// only on page edits screens
if($this->process != "ProcessPageEdit") return;
$field = $event->object;
// no tinymce fields
if($field == "InputfieldTinyMCE") return;
// get field to set attribute, will get rendered by the InputfieldTexarea
$inputfield = $this->fields->get($field->name);
$field->attr("data-maxlength", $inputfield->maxchars);
}
public function renderTextarea(HookEvent $event){
// add stuff only to admin pages edit screen
if($this->process != "ProcessPageEdit") return;
// not render span if tinymce field
if($event->object == "InputfieldTinyMCE") return;
// add scripts to admin page
$this->config->scripts->add($this->config->urls->TextAreaCounter . "TextAreaCounter.js");
// add span to render counter
$max = $this->fields->get($event->object->name)->maxchars;
$value = $event->object->value;
$left = $max - strlen($value);
$event->return .= "<span class='counter'>".$this->_("Chars left").": <span>$left</span></span>";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment