php-censor/src/B8Framework/Form/FieldSet.php

119 lines
2.5 KiB
PHP
Raw Normal View History

2016-04-12 19:31:39 +02:00
<?php
namespace b8\Form;
2016-04-20 17:39:48 +02:00
2017-11-05 15:48:36 +01:00
use b8\View;
2016-04-12 19:31:39 +02:00
class FieldSet extends Element
{
2017-11-05 15:48:36 +01:00
/**
* @var Element[]
*/
2016-04-20 17:39:48 +02:00
protected $_children = [];
2017-11-05 15:48:36 +01:00
/**
* @return array
*/
2016-04-20 17:39:48 +02:00
public function getValues()
{
$rtn = [];
foreach ($this->_children as $field) {
if ($field instanceof FieldSet) {
$fieldName = $field->getName();
if (empty($fieldName)) {
$rtn = array_merge($rtn, $field->getValues());
} else {
$rtn[$fieldName] = $field->getValues();
}
} elseif ($field instanceof Input) {
if ($field->getName()) {
$rtn[$field->getName()] = $field->getValue();
}
}
}
return $rtn;
}
2017-11-05 15:48:36 +01:00
/**
* @param array $values
*/
2016-04-20 17:39:48 +02:00
public function setValues(array $values)
{
foreach ($this->_children as $field) {
if ($field instanceof FieldSet) {
$fieldName = $field->getName();
if (empty($fieldName) || !isset($values[$fieldName])) {
$field->setValues($values);
} else {
$field->setValues($values[$fieldName]);
}
} elseif ($field instanceof Input) {
$fieldName = $field->getName();
if (isset($values[$fieldName])) {
$field->setValue($values[$fieldName]);
}
}
}
}
2017-11-05 15:48:36 +01:00
/**
* @param Element $field
*/
2016-04-20 17:39:48 +02:00
public function addField(Element $field)
{
$this->_children[$field->getName()] = $field;
$field->setParent($this);
}
2017-11-05 15:48:36 +01:00
/**
* @return boolean
*/
2016-04-20 17:39:48 +02:00
public function validate()
{
$rtn = true;
foreach ($this->_children as $child) {
if (!$child->validate()) {
$rtn = false;
}
}
return $rtn;
}
2017-11-05 15:48:36 +01:00
/**
* @param View $view
*/
2017-01-13 16:35:41 +01:00
protected function onPreRender(View &$view)
2016-04-20 17:39:48 +02:00
{
$rendered = [];
foreach ($this->_children as $child) {
$rendered[] = $child->render();
}
$view->children = $rendered;
}
2016-04-12 19:31:39 +02:00
2017-11-05 15:48:36 +01:00
/**
* @return Element[]
*/
2016-04-12 19:31:39 +02:00
public function getChildren()
{
return $this->_children;
}
2017-11-05 15:48:36 +01:00
/**
* @param string $fieldName
*
* @return Element
*/
2016-04-12 19:31:39 +02:00
public function getChild($fieldName)
{
return $this->_children[$fieldName];
}
2016-04-21 19:05:32 +02:00
}