0

I've a taxonomy tree used in an entity reference field, which requires some custom rules (e.g. if any option of subtree A is chcked, then any option of subtree B is disallowed or if any option of subtree C is checked, parents must be checked too).

The field widget for this tree is set to multi-value option buttons (checkboxes). I need to create some JS behaviors that assist editors with those rules during input. I need extra info from the taxonomy term entity so my JS behaviors can act on it.

Currently the form element if rendered like this:

<input data-drupal-selector="edit-FIELD-MY-TAXONOMY-ID" type="checkbox" id="edit-FIELD-MY-TAXONOMY-ID" name="FIELD-MY-TAXONOMY[ID]" value="ID" class="form-checkbox form-boolean form-boolean--type-checkbox">

I need extra informatio like this

<input data-term-parent-id="XXX" data-term-field-foo-value="YYY" ...>

I know how to write PHP entity queries and the JS, but I don't know which hook to use to inject my those attributes. I've tried hook_field_widget_single_element_form_alter , hook_field_widget_complete_form_alter and template_preprocess_form_element - and not a single one of these contains information about the taxonomy term entity or the vocabulary, they all just "see" the IDs and labels as strings (and the label strings are not even the term titles, they have - in front if them due hierarchy).

The taxonomy is used in multiple nodes with multiple different field names, so guessing on field name is not a good idea. Which hook allows me to alter the checkbox form element AND contains a reliable link to the reference entity object?

1 Answer 1

1

I've tried hook_field_widget_single_element_form_alter , hook_field_widget_complete_form_alter ... and not a single one of these contains information about the taxonomy term entity or the vocabulary ... contains a reliable link to the reference entity object?

The main object for fields is the field item list, which is provided in $context. From there you can go up to get the parent entity:

$entity = $context['items']->getEntity();

or downstream to get the referenced entities. See https://drupal.stackexchange.com/a/309863/47547

Which can be taxonomy terms depending on whether you have placed the field in a vocabulary or your field is storing references to taxonomy terms. In either case the bundle name is the vocabulary.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.