a12s-1.0.0-beta7/src/FormHelperTrait.php
src/FormHelperTrait.php
<?php
declare(strict_types=1);
namespace Drupal\a12s_core;
trait FormHelperTrait {
/**
* Get the name of an input element from its path.
*
* Nested input names are based on the hierarchy of the element inside the
* form. So when we use #states API, we may need to target a specific
* element with its name.
*
* With the following arguments:
* - select
* - ['foo', 'bar']
* - 'baz'
*
* The method will return the following string:
* - select[name="foo[bar][baz]"]
*
* @param string $type
* The input type. It can also be ":input", which includes several elements
* like <button>, <textarea>, <select>...
* @param string|array ...$keys
* Each parameter is either a string or an array of strings, which define
* all together the path of the input element.
*
* @return string
* The path selector.
*/
protected function getInputNameFromPath(string $type, string|array ...$keys): string {
$name = $this->getInputSelectorFromPath(...$keys);
return $name ? $type . '[name="' . $name . '"]' : '';
}
/**
* Get the selector of an input element from its path.
*
* Nested input selectors are based on the hierarchy of the element inside
* the form. This method can be used to target a specific element with its
* selector.
*
* With the following arguments:
* - ['foo', 'bar']
* - 'baz'
*
* The method will return the following string:
* - 'foo[bar][baz]'
*
* @param string|array ...$keys
* Each parameter is either a string or an array of strings, which define
* all together the path of the input element.
*
* @return string
* The input element selector.
*/
protected function getInputSelectorFromPath(string|array ...$keys): string {
if ($keys) {
$parents = array_reduce($keys, fn($parents, $key) => array_merge($parents, (array) $key), []);
$root = array_shift($parents);
return $root . ($parents ? '[' . implode('][', $parents) . ']' : '');
}
return '';
}
}
