7

I'm usign the module Paragraphs for Drupal 8. I need to print the raw value of a paragraph field in the twig template, so I'm trying to access to the value of the field in the hook_preprocess_field, but I don't know how to access the value in $variables.

Any idea?

3 Answers 3

4

You can use preprocess field hook which is supported in drupal 8 also . Example below:

function example_preprocess_field(&$variables) {
    if (($variables['element']['#field_name'] == 'example')) {
    //get the value of the field
    dsm($variables);
   print_r($variables);
    // add a class to the field        
    $variables['attributes']['class'] = [
     'example'
      ];
  }
}
3
  • dsm function needs devel module, so before running this code install that module. Commented Sep 7, 2016 at 16:25
  • Thank you for your replies. But I don't know why when I print the content of the array in the hook_preprocess_field, the value of that field is not present. Maybe because it is part of a paragraph field, I don't know. I could achieve what I needed using the variable paragraph instead of content in the twig template like in drupal.org/node/2662400 where it describes exactly the same scenario I have.
    – jmzea
    Commented Sep 7, 2016 at 17:26
  • Yes, the values of paragraph fields are in the variable paragraph, but not in field.html.twig, but in paragraph.html.twig.
    – 4uk4
    Commented Sep 7, 2016 at 18:24
4

To get at the value of a paragraphs field for manipulation etc you can use template_preprocess_paragraph(&$variables) or more specifically template_preprocess_paragraph__PARAGRAPH_TYPE(&$variables)

0

One Good solution for that is to first install Devel module and then you can use dsm function.

this function is easy to use just write dsm($variables) and it will print a hierarchical form of element.

Using that you will know how to have access to your desired values and fields.

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.