Thursday 1 September 2016

Drupal 7 Form API displaying only the Parent options in an Entity / Content Field item

So what I have is a Content Form where I want to display a Term / Taxonomy but only the Parent items for the moment.

Here's a way of solving this programmatically in a Hook Form Alter.

In my hook_form_FORM_ID_alter I iterate through the options array and remove the child choices. This is easy as those choices start with a minus sign .

  foreach ($form['my_field']['und']['#options'] as $key => $value) {
   // if $value starts with '-' then its a child item and I'll unset it.
    if ($value[0] == '-'){
      unset($form['my_field']['und']['#options'][$key]);
    }

  }

No comments: