I'm new to Drupal and still have to figure out a lot. This might also be just a general programming question.
I wrote a module that has some js-libraries which should be attached to forms on different conditions. For one of those libraries, I want to add it in case the form array has an element with the class "remove-button", which could be at any depth.
I searched for different recursive approaches, but it doesn't work somehow. I was able to attach the library without a condition so it attaches to all forms, so the problem lies within my recursive function.
Snippet from hook_form_alter in my .module file:
function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id)
{
// remove-button
$hasRemoveButton = containsClass($form, 'remove-button');
if ($hasRemoveButton) {
$form['#attached']['library'][] = 'my_module/remove-button';
}
}
Recursive search function (last code I tried):
/**
* Search a class in $form.
*/
function containsClass($array, $class)
{
if (!is_array($array)) {
return false;
}
if (isset($array['class']) && in_array($class, $array['class'])) {
return true;
}
foreach ($array as $subarray) {
containsClass($subarray, $class);
}
}
Anyone an idea how this can be achieved? Maybe with a different approach than a recursion?