2

On my node edit form a term reference field is rendered with the following html output:

<div class="form-item form-type-radio form-item-field-trainingstype-und">
  <input type="radio" id="edit-field-trainingstype-und-12" name="field_trainingstype[und]" value="12" class="form-radio">  
  <label class="option" for="edit-field-trainingstype-und-12">External </label>
</div>

As you can see the value attribute is set to 12 which is the term id of that particular item. Now I would like to replace 12 with the term name, External.

So it would look like:

<div class="form-item form-type-radio form-item-field-trainingstype-und">
  <input type="radio" id="edit-field-trainingstype-und-12" name="field_trainingstype[und]" value="External" class="form-radio">  
  <label class="option" for="edit-field-trainingstype-und-12">External </label>
</div>

I am unsure which function to use to target this particular field. I was looking at theme_checkbox() and theme_form_element() but I am uncertain how to proceed and if these are the right functions for the job.

UPDATE: So I would like to show another field based on the option chosen for the field_trainingstype. In a hook_form_alter I am now doing this:

$form['field_organisaton']['#states'] = array(
  'visible' => array(
    ':input[name="field_trainingstype[und]"]' => array('value' => '12'),
  ),
);

But I would like to trigger this by term name External because the term id might differ per environment.

2

Doing it that way round will cause problems with the form submission; the value for a term reference field needs to be an integer and throwing a string at it will undoubtedly upset things. You could massage values back into place in a validate function but it seems a bit...messy.

The alternative would be to load the taxonomy term up in the form, so you can use the ID from there:

$terms = taxonomy_get_term_by_name('External', 'vocab_machine_name');
$term = array_shift($terms);
$form['field_organisaton']['#states'] = array(
  'visible' => array(
    ':input[name="field_trainingstype[und]"]' => array('value' => $term->tid),
  ),
);

That should make it reusable across different environments (provided the vocab only has one term with the name "External").

| improve this answer | |
  • Arghh, ofcourse. Was thinking the other way around. Thanks. – undersound Oct 8 '14 at 19:11
  • taxonomy_get_term_by_name() returns an array of term objects, indexed by tid. So in my case, where I am sure I have only one term with the name External I could and have to do this $term = reset(taxonomy_get_term_by_name('Extern', 'trainingstypen')); – undersound Oct 8 '14 at 21:00
  • So it does @undersound, sorry about that – Clive Oct 8 '14 at 21:57

Your Answer

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

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