1

I am trying to add an attribute of "id="background" to the actual image tag.

<?php print render($content['field_bg_image']); ?>

I've looked up tons of articles and they are all concerned with hook_form_alter and this is not a form. This is simply just an image field, I just need an ID attribute on it with a value of background. I know I can use javascript but I want to use Drupal and not add any more javascript.

josephleon
  • 1,219
  • 2
  • 9
  • 8

2 Answers2

5

The image render is run through theme_image_formatter() which doesn't let you set attributes.

You can get around this by building the image up manually:

$img = theme('image', array(
  'path' => $content['field_bg_image'][0]['#item']['uri'],
  'alt' => $content['field_bg_image'][0]['#item']['alt'],
  'attributes' => array('id' => 'background')
));

$content['field_bg_image'][0] = array(
  '#markup' => $img
);

echo render($content['field_bg_image']);

That's untested so let me know if you have any problems

Clive
  • 36,918
  • 8
  • 87
  • 113
0

You could use a template for your cck field, in your case the name of this file could be field--field-bg-image.tpl.php and should be put inside your current theme folder, then you could add your id attribute like this:

 // in field--field-bg-image.tpl.php
 <div id="your-id" class="<?php echo $classes; ?>">
    <?php print render($items); ?>
 </div>    

Have a look at field.tpl.php

If you wan't to set the id on the actual img tag you could do something along these lines in your field--field-bg-image.tpl.php file:

$object = $element['#object']; 
$data = $object->field_bg_image[$object->language][0];
$fid = $data['fid'];
$width = $data['width'];
$height = $data['height'];  
print '<img id="your-id" src="'.file_create_url(file_load($fid)->uri).'" width="'.$width.'" height="'.$height.'" />';

You may also checkout theme_image() and do like this:

print theme_image(
         array('path'=>file_load($fid)->uri,
               'attributes'=>
                   array('alt'=>'','id'=>'your-id')
         )
      );
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
  • I was just going to recommend using a template as the preferred way to handle this. – Patrick Jan 19 '12 at 20:30
  • @pthurmond: A template won't work in this case, OP wants to add an ID to the image tag itself not the field container. You could override the theme registry but I'm not sure that's worth the effort it's just an isolate incident like a page background – Clive Jan 19 '12 at 20:34
  • @Clive: I have done this before in similar situations and you can almost always create a low level enough template override to add to an individual tag. It really depends on if the image tag that is output exists in a template or is constructed in the control code. I would have to look it up but I am pretty sure that CCK has templates at a low enough level to accomplish this. – Patrick Jan 19 '12 at 20:52