1

I have a Drupal code below:

function myid_create_template($form, &$form_state){ 
    $form['myid_templates_editor']['#access'] = TRUE;    
    foreach (element_children($form['myid_templates_editor']) as $child1)   {
        $form['myid_templates_editor'][$child1]['#access'] = TRUE;

    }     
    return $form;
}

This code iterate to the first child only of an element, but not the child with degree 2 or more. How will I iterate it to all child/grandchild of the element?

4

A simple recursive function will do the trick:

function allow_access(&$root_element) {
  $root_element['#access'] = TRUE;
  foreach (element_children($root_element) as $key) {
    allow_access($root_element[$key]);
  }
}
allow_access($form);
  • This is what I've been looking for. I thought it would work but unfortunately not. I updated my post above and will gladly appreciate you if u could point me into the right direction. Thanks :) – user46175 Nov 5 '15 at 3:04
  • This should work fine with a slight modification - you need to check that $root_element is an array. Otherwise element_children throws a warning. – argiepiano Jun 17 at 2:17
-1

I believe you will have to manually add support for 2nd/3rd/etc. levels.

Didn't test the code, but this should point you in the right direction:

function myid_create_template($form, &$form_state){ 
  $form['myid_templates_editor']['#access'] = TRUE;    
  foreach (element_children($form['myid_templates_editor']) as $child1) {
    // Check if this element is a parent of another element.
    if (count(element_children($form['myid_templates_editor'][$child1]))) {
      foreach (element_children($form['myid_templates_editor']) as $child2) {
        if (count(element_children($form['myid_templates_editor'][$child1][$child2]))) {
          foreach (element_children($form['myid_templates_editor']) as $child3) {
            // You can continue to search for more levels here, if necessary.
          }
        }
        else {
          $form['myid_templates_editor'][$child1][$child2][$child3]['#access'] = TRUE;
        }
      }
    }
    // This is just a regular element.
    else {
      $form['myid_templates_editor'][$child1]['#access'] = TRUE;
    }
  }     

  return $form;
}
  • Thank you for your idea but what if I had 100'th degree child? Do I have to hard code all of those? I guess recursion will do the trick, but I dont know how to implement it. :) – user46175 Nov 4 '15 at 8:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy