0

I have added a field to content types so that users can upload a custom background image based on content type. This is a Drupal 8 site.

The field is set as required and has a default image uploaded to it.

I then have the following code in my theme_preprocess_page function:

  /* Setup custom variables from the content type for reskinning */
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    if ($node->field_background) {
       $variables['mybg']=file_create_url($node>field_background->entity->getFileUri());
    }
   }

I want to access the above in the page.html.twig template with:

 style="background-image:url({{ mybg }});"

So I can set the background of the page header.

After clearing cache and reloading the page however I get:

 The website encountered an unexpected error. Please try again later.
 Error: Call to a member function getFileUri() on null in mytheme_theme_preprocess_page()

If I manually add a file to a specific page, then it works fine. However, I want the default to actually work as my users want to set a bg once for each content type.

Shouldn't the default appear as the field if no other value was added?

For clarity: My above code works if the image field has been added to on the specific node, however, The default value for the field is not being loaded in its absence. How do I access the default value for the field?

Browse other questions tagged or ask your own question.