I am implementing a hook_form_alter in my custom module and I want to get all the inputs from the $form variable.

So, if for example there is a textarea, a radio button and a checkbox, I want to grab these elements and put them in a clean array for later use. What I basically want to do down the road is create a dropdown list and have these inputs as the options in the list.

Is this a clean way to do that through the FAPI?

3 Answers 3


You can use the element_children() function to grab all of the child elements within a particular element (including a form element). The thing with Drupal forms is that often all elements are not on the same level of the array, so you'll need to make a recursive function to get them all reliably. This is untested but should give you a place to start:

function _element_children_recursive(&$element) {
  $names = array();

  foreach (element_children($element) as $element_key) {
    $names[] = $element_key;
    $names = array_merge($names, _element_children_recursive($element[$element_key]));

  return $names;

$all_element_names = _element_children_recursive($form);

There's even one further caveat to this...since form elements can be on different levels you might well end up with two identically named keys. This is perfectly valid in Drupal so you'll probably want to do a bit of checking in the recursive function to avoid duplicates.

  • 1
    I used the idea in your answer, but my code looks like this: pastebin.com/csJstrwT (added some restrictions to keep only the elements that are visible to, and accessible by, the user)
    – user6102
    Commented Mar 24, 2012 at 14:37

Do you want the FAPI representation of the elements or the user-inputted values?

I think that you are asking about the values input to the form elements by the user. These are available in the variable $form_state['values'] when the form has been submitted.

  • No, I'm actually asking about the FAPI representation of the elements. Ultimately I want to grab all the form elements that are visible to the user when he sees the form.
    – user6102
    Commented Mar 23, 2012 at 19:00

I think the accepted answer is the best, but I wanted to mention you can also get the field names by doing drupal_retrieve_form('form_id', $form_state). You get an array with the form element names as keys, and the build attribute array of each field as the contents.

Note: you have to create a dummy $form_state by doing $form_state['build_info']['args'] = array();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.