TextAreaCounter concept module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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