0

I am trying to change the display label of one field on a node (not the form), depending on the value set in another field in Drupal 7. I don't want to change the label in the database, just on the final node page when you view it, if another field is set to a certain value.

I tried a few different hooks with no luck. Some can access every field, but only the value and not the label. Some can access the label on a per field basis which I can get half working (Set a flag in another function if the field is set correctly) but that only worked if the fields are checked in the right order.

So which painfully obvious hook will allow me to check a field setting and then edit the display of a label on another only on the node page? My perusing of the hook documentation and Google have not helped.

Thanks!

1

A guaranteed solution for all fields is hard. It depends on:

  1. The field formatters you have chosen
  2. the template files used

For a general approach try:

/**
 * Implements hook_preprocess_HOOK().
 */
function YOUR_MODULE_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'YOUR_DEPENDENT_FIELD' && !empty($variables['element']['#object']->YOUR_DEPENDENCY_FIELD)) {
    // YOUR LOGIC IN RELATION TO YOUR_DEPENDENCY_FIELD
    $new_value = 'something';
    $variables['label'] = $new_value;
  }
}

Notes:

  1. This will change the label display everywhere, not only on a node display. Since you don't mention anything about view modes, I guess the given solution is good enough.
  2. Make sure you sanitize $new_value if you are showing user input.
  • So, I can make this work but it has some issues (I think). Each call of hook_preprocess_field only has access to that field. I can't check the dependee field and then set the label for the dependent field in the same call. I would have to check the dependee field, set a variable in a custom function and then check that custom function for each call to hook_preprocess_field. This will only work if the 2 fields are called in the correct order. That is the case right now, but will likely change down the road. – Comprox Apr 28 '16 at 19:00
  • You can manage all in once, no need for variable_set(). In that hook you have access to the complete object (node) the field is attached to. I take, that both the field you want to change, as the field you need to check are on the same node? You can access the field value you need to check: $variables['element']['#object']->YOUR_DEPENDENCY_FIELD. – dmsmidt Apr 29 '16 at 7:58
0

Seems I forgot to log in last time and it's not letting me mark that as the answer. dmsmidt was exactly correct. I just had to dig a little deeper in DPM to find the info I needed. Thanks!

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.