- Issue created by @mlncn
- πΊπΈUnited States mlncn Minneapolis, MN, USA
It is not hard to use the provided taxonomy_machine_name_term_load() function to do this; but the module page documentation should add the modern Drupal section (the function name has been corrected since D7).
foreach ($search_fields as $key => $field) { $zip_term = taxonomy_machine_name_term_load('zip_code', 'search_by'); if ($field === 'field_search_zip' || $field === 'field_search_radius') { $form[$field]['#states'] = [ 'visible' => [ ':input[name="field_search_by"]' => ['value' => $zip_term->id()], ], ]; } $county_term = taxonomy_machine_name_term_load('county', 'search_by'); if ($field === 'field_address_county') { $form[$field]['#states'] = [ 'visible' => [ ':input[name="field_search_by"]' => ['value' => $county_term->id()], ], ]; } }
(this is looping
- πΊπΈUnited States mlncn Minneapolis, MN, USA
This is very silly, but made a helper module to do this: Taxonomy Machine Name Helper β
Now my code (note as before it loops through fields, which is a little unusual for this but doesn't change how this helper function is used really) looks like this:
if ($field === 'field_search_zip' || $field === 'field_search_radius') { taxonomy_machine_name_helper_set_dependent_field_state($form, 'field_search_by', 'zip_code', 'search_by', $field); } elseif ($field === 'field_address_county') { taxonomy_machine_name_helper_set_dependent_field_state($form, 'field_search_by', 'county', 'search_by', $field); }
The signature of the function being used there is:
/** * Set form field state based on term machine name in controlling field. * * @param array $form * Form to make the changes to. * @param string $controlling_field * Machine name for the controlling field (must have options that are taxonomy terms). * @param string $term_machine_name * Term machine name that triggers target field behavior (must be provided by Taxonomy Machine Name module). * @param string $target_field * Machine name for the target field. * @param string $state * Optional state to put the target field in when the term matching the term machine name is selected. Defaults to 'visible'. */ function taxonomy_machine_name_helper_set_dependent_field_state(&$form, $controlling_field, $term_machine_name, $vocabulary, $target_field, $state = 'visible')
It also checks that it can load a term of the given machine name, and logs a warning rather than blowing anything up if it cannot, and abstracting that code for re-use is really what tipped me into making it a contribution.
I made a separate module because i didn't really see this being accepted as a feature request but would happily roll it into taxonomy_machine_name itself if it is welcome.