SubformState.php in Drupal 10
File
core/lib/Drupal/Core/Form/SubformState.php
View source
<?php
namespace Drupal\Core\Form;
use Drupal\Component\Utility\NestedArray;
class SubformState extends FormStateDecoratorBase implements SubformStateInterface {
use FormStateValuesTrait;
protected $parentForm;
protected $subform;
protected function __construct(array &$subform, array &$parent_form, FormStateInterface $parent_form_state) {
$this->decoratedFormState = $parent_form_state;
$this->parentForm = $parent_form;
$this->subform = $subform;
}
public static function createForSubform(array &$subform, array &$parent_form, FormStateInterface $parent_form_state) {
return new static($subform, $parent_form, $parent_form_state);
}
protected function getParents($property) {
foreach ([
$this->subform,
$this->parentForm,
] as $form) {
if (!isset($form[$property]) || !is_array($form[$property])) {
throw new \RuntimeException(sprintf('The subform and parent form must contain the %s property, which must be an array. Try calling this method from a #process callback instead.', $property));
}
}
$relative_subform_parents = $this->subform[$property];
foreach ($this->parentForm[$property] as $parent_form_parent) {
if ($parent_form_parent !== $relative_subform_parents[0]) {
throw new \UnexpectedValueException('The subform is not contained by the given parent form.');
}
array_shift($relative_subform_parents);
}
return $relative_subform_parents;
}
public function &getValues() {
$exists = NULL;
$values =& NestedArray::getValue(parent::getValues(), $this
->getParents('#parents'), $exists);
if (!$exists) {
$values = [];
}
elseif (!is_array($values)) {
throw new \UnexpectedValueException('The form state values do not belong to the subform.');
}
return $values;
}
public function getCompleteFormState() {
return $this->decoratedFormState instanceof SubformStateInterface ? $this->decoratedFormState
->getCompleteFormState() : $this->decoratedFormState;
}
public function setLimitValidationErrors($limit_validation_errors) {
if (is_array($limit_validation_errors)) {
$limit_validation_errors = array_merge($this
->getParents('#parents'), $limit_validation_errors);
}
return parent::setLimitValidationErrors($limit_validation_errors);
}
public function getLimitValidationErrors() {
$limit_validation_errors = parent::getLimitValidationErrors();
if (is_array($limit_validation_errors)) {
return array_slice($limit_validation_errors, count($this
->getParents('#parents')));
}
return $limit_validation_errors;
}
public function setErrorByName($name, $message = '') {
$parents = $this->subform['#array_parents'];
$parents[] = $name;
$name = implode('][', $parents);
parent::setErrorByName($name, $message);
return $this;
}
}