0

I am trying to alter how a field is displayed with hook_preprocess_field(). This is the code I added to the theme's template.php.

function creative_responsive_theme_preprocess_field(&$vars) {
  $element = &$vars['element'];
  if ($element['#field_name'] == 'field_myfield') {
    $element['#items'][0]=[];
    $element['#items'][0]['value'] = 'replaced value';
    $element['#items'][0]['format'] = 'filtered_html';
    $element['#items'][0]['safe_value'] ='';
    $element['#items'][0]['#markup'] = 'replaced value';
  }
}

The code is executed, but the page does not show what I added. The field is being displayed as usual. I am using the Display Suite module.

I am not sure if that effects anything, but searching online, I see no indication that above should not work. I added the #markup part because I read that is truly what one has to do.

Do you have ideas?

1 Answer 1

1

I think it was the # in front of items that was messing things up. I have this working now.

function creative_responsive_theme_preprocess_field(&$variables) {
  if (user_is_logged_in()) {
    return $variables;
  }
  if (($variables['element']['#field_name'] == 'field_audio_fast_') OR ($variables['element']['#field_name'] == 'field_audio_slow_')) {
    $variables['items'][0]=[];
    $variables['items'][0]['value'] = '<a href='.'"/user/register?destination=[path]"> <img src="/images/play.gif"></a>';
    $variables['items'][0]['format'] = 'full_html';
    $variables['items'][0]['safe_value'] ='';
    $variables['items'][0]['#markup'] = '<a href='.'"/user/register?destination=[path]"> <img src="/images/play.gif"></a>';
    return $variables;
  }
}

At first, $variables['items'][0]=[]; was producing a bunch of warnings about invalid arguments to core functions regarding children and parents and rendering. Then I cleared the cache. The thing is, the field I am replacing is an audio file field. So I think there must be a cleaner way to do this than above.

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