I need this to store numeric values for the 12 months. These will be used to render a chart on page. So I first did a simple textarea and having each values on a new line, but wanted something more intuitive and convienient for the client to enter the values.
(I know it would also be possible (and maybe better solution) to write a complete new Fieldtype/Inputfield, but I'm not really into it yet and would need some help. But this was kinda simple and does the job, only drawback is that it wouldn't work with selectors as it's stored as json in a text field in db.)
Here's my code:
<?php
/**
* ProcessWire Custom InputfieldMonths
*
* Inputfield that stores numeric values for the 12 months of a year.
*
*/
class InputfieldMonths extends InputfieldTextarea {
protected $months = array(
"January" => "jan",
"February" => "feb",
"March" => "mar",
"April" => "apr",
"May" => "may",
"June" => "jun",
"July" => "jul",
"August" => "aug",
"September" => "sep",
"October" => "oct",
"November" => "nov",
"December" => "dec"
);
public static function getModuleInfo() {
return array(
'title' => 'InputfieldMonths',
'version' => 100,
'summary' => 'Stores 12 integer values for months of a year',
'permanent' => false,
);
}
public function init() {
parent::init();
}
public function ___render() {
$values = json_decode($this->value,true);
$out = '';
foreach($this->months as $label => $name) {
$out .= <<< _OUT
<p>
<label for='$name'>$label</label>
<input id='$name' name='$name' value='$values[$name]'/>
</p>
_OUT;
}
return $out;
}
public function ___processInput(WireInputData $input) {
foreach($input as $key => $val) {
if(!in_array($key, $this->months) or $val === '') continue;
if(!is_numeric($val)) return $this->error("Wrong format. Value '$val' is not numeric!");
}
$months_values = array();
foreach($this->months as $month) {
$months_values[$month] = $input[$month];
}
$data = json_encode($months_values);
if($this->value != $data) {
parent::trackChange('value');
$this->value = $data;
}
return $this;
}
}












