7

I need to preprocess the field values of a paragraph bundle to "send" additional variables to the template (paragraphs-item--xxxx--full.tpl.php). I want to avoid putting too much php logic into the paragraph template.

I am searching for something similiar to the node_view hook for a paragraph item. Is there a fitting mechanism or maybee a module providing such an hook?

11

Drupal 7

I don't know if this will help you directly, but I found this code snippet on DropBucket and it helped me do something similar:

/**
 * Implements hook_preprocess_entity().
 */
function wwvs_slices_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    $edge = field_get_items('paragraphs_item', $variables['paragraphs_item'], 'field_edge');
    if ($edge && $edge[0]['value']) {
      $variables['classes_array'][] = 'slice--edge';
    }
  }
}

In my usecase I wanted to augment the paragraph entity with an ID using the url-safe version of the title field used in that paragraph. Here's my implementation:

/**
 * Implements hook_preprocess_entity().
 */
function foo_preprocess_entity(&$variables) {
  if ($variables['entity_type'] == 'paragraphs_item') {
    if(isset($variables['elements']['pp_title']['#items'][0]['value'])){
      $title = $variables['elements']['pp_title']['#items'][0]['value'];
      $title = strtolower(drupal_clean_css_identifier($title));
      $variables['attributes_array']['id'] = $title;
    }
  }
}

I hope this is helpful!

6

Drupal 8

In Drupal 8 you can use hook_preprocess_HOOK:

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_paragraph(&$variables) {

}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_paragraph__TYPE(&$variables) {

}

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.