Custom templating Fields/CCK field output
The Drupal theming and templating possibilities are endless and once you get how it's done it's a breeze! I say once you get it, because you can have a hard time figuring out how. For the next version of my portfolio website, which I'm building in Drupal 7, I had a hard time figuring out how to override the HTML that was generated automatically by Drupal for a Fields (former CCK) field. I had a custom content type with a multiple value image field from Fields (the 'new' CCK in Drupal 7) plus some other more standard fields.
Working with the Views 2 module and creating some custom templates for the output I was able to generate my own clean and minimal HTML without all the extra div's and wrappers the Views Module can provide. There was however one problem, I could not figure out how to have the image field rendered without the div wrapper and field label divs. Here's what it looked like:
<div class="Custom-Div">
<div class="field field-name-field-photo field-type-image field-label-hidden">
<div class="field-items">
<div class="field-item even"><img alt="" /></div>
</div>
</div>
</div>
Now that's a lot of DIV! What I wanted to achieve was to loose all the extra DIV's and just have my Custom-Div containing all the image fields, like this:
<div class="Custom-Div">
<img ..... />
<img ..... />
..................
</div>
At first I thought this could easily be achieved with the Views templating possibilities, using views-view-fields.tpl.php to customize my output. For all fields that worked fine except for this Fields/CCK image field! Searching for options in other Views templates or writing out the raw query result via some custom code couldn't help me. Then all of a sudden I started realising I was looking in the wrong place! The extra HTML was generated because this image field was a Fields (CCK) field added to the content type. I found an article explaining this for the Drupal 6 CCK fields. So I started searching for the same info in my Drupal folders in the Fields section and voila!
Fields/CCK have a custom theme function for generating the field output! And it works almost similar overwriting this with you custom code. Even for single CCK fields. You can find the file field.tpl.php in the Fields module folder structure that comes with Drupal 7 core. Just copy this file to your theme folder, modify it to your needs and you're done!
If you want it to apply to only one certain field use the name of that field in the file name like field-[FIELD_NAME].tpl.php. Heck, you can even narrow it down to certain content types by adding field-[FIELD_NAME]-[CONTENT_TYPE].tpl.php to the file name.
Sometimes, the simplest solutions are the hardest to find.
drupal web development
Post new comment