From 764153732eba0ed05b24dba4e9cda9d2d2eb42d3 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Fri, 17 May 2024 11:09:03 -0400 Subject: [PATCH] Add new InputfieldWrapper getByField() and getByProperty() methods --- wire/core/InputfieldWrapper.php | 58 +++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/wire/core/InputfieldWrapper.php b/wire/core/InputfieldWrapper.php index 9bf7328b..fb3d891e 100644 --- a/wire/core/InputfieldWrapper.php +++ b/wire/core/InputfieldWrapper.php @@ -1566,6 +1566,64 @@ class InputfieldWrapper extends Inputfield implements \Countable, \IteratorAggre return $inputfield; } + /** + * Get Inputfield by Field (hasField) + * + * This is useful in cases where the input name may differ from the Field name + * that it represents, and you only know the field name. Applies only to + * Inputfields connected with a Page and Field (i.e. used for page editing). + * + * #pw-group-retrieval-and-traversal + * + * @param Field|string|int $field + * @return Inputfield|InputfieldWrapper|null + * @since 3.0.239 + * + */ + public function getByField($field) { + if(!$field instanceof Field) $field = $this->wire()->fields->get($field); + return $this->getByProperty('hasField', $field); + } + + /** + * Get Inputfield by some other non-attribute property or setting + * + * #pw-group-retrieval-and-traversal + * + * @param string $property + * @param mixed $value + * @param bool $getAll Get array of all matching Inputfields rather than just first? (default=false) + * @return Inputfield|InputfieldWrapper|null|array + * @since 3.0.239 + * + */ + public function getByProperty($property, $value, $getAll = false) { + $inputfield = null; + $value = (string) $value; + $a = array(); + + foreach($this->children() as $child) { + /** @var Inputfield $child */ + if((string) $child->getSetting($property) === $value) { + $inputfield = $child; + } else if($child instanceof InputfieldWrapper) { + if($getAll) { + $a = array_merge($a, $child->getByProperty($property, $value, true)); + } else { + $inputfield = $child->getByProperty($property, $value); + } + } + if($inputfield) { + if($getAll) { + $a[] = $inputfield; + } else { + break; + } + } + } + return $getAll ? $a : $inputfield; + } + /** * Get value of Inputfield by name *