Search code examples
phpdrupaldrupal-7drupal-theming

Notice: Undefined offset: 0 when field is empty


I'm trying to print out an image as a background image in a voews-view-field.tpl file. Below is the code I'm using. It works perfectly when there is an image. When there is no image however, I still want it to render the rest of the output with no background image, but I get the following error:

Notice: Undefined offset: 0 in include() (line 26 of .../templates/views-view-field--nothing.tpl.php).

the error is pointing to the first line of code. I'm assuming I need to somehow add in if(isset) here, but I can't figure out where exactly to put it...nothing I've tried has worked. Or maybe that's just not the problem. Any help would be much appreciated! Thanks!

<?php
    $url = file_create_url($row->field_field_parallax_image[0]['raw']['uri']);
    $url = parse_url($url);
    $path = $url['path'];
?>
<div class="parallax" style="background-image: url('<?php 
    if(isset($row->field_field_parallax_image)) print $path; ?>');">
    <?php print $output; ?>
</div>

Solution

  • Replace 1st line with:

    if (isset($row->field_field_parallax_image[0]))
    {
       $url = file_create_url($row->field_field_parallax_image[0]['raw']['uri']);
    }