Problem
When using Code Fields we have very few options and variables to play with: global $conf, current $theme and $entity which was not 'viewed' and thus - w/o renderable array for itself and fields. So its no so much we can do and we have no access to already built fields.
Soluition
First - expose $build to Code Fields.
It is very simple fix, which brings power to Code Fields. All we need is $build array where all the stuff are ready to reneder.
Second - hide fields which are printed from a code field
If a field is not added to a region - it won't be built. So we should first add a field to some region and then use it in the code field. But in this case a field will be displayed twice! So we need a way to hide fields.
Previously I was trying to use some fields in code and came up to this solution. I don't like it anymore. Reason - hiding a field in this way will hide it in code field also :) So we either get duplicates or nothing.
Another approach is to add a special region "Hidden" which name is self explaining - you just put some fields into there and - TADA - they are built, configured and ready to print, but are hidden until you output them from the code.
Implementation
Patch provided.
How to use it
1. Place a field into region Hidden
2. Now in a code field you can:
Render everything:
print render($build);
Render a field:
print render($build['field_photo'][0]);
Use field values or field view:
print l(render($build['field_photo'][0]), $build['field_link']['#items'][0]['display_url'], array('html' => TRUE));
Note, that taking field values from $build array is much more straightforward:
print $build['field_link']['#items'][0]['display_url'];
then using $entity:
print $entity->field_link['und'][0]['display_url'];
because you got rid of calculating language code.
P.S. Adding $build called for changing functions arguments, and to not break existing stuff (which probably call ds functions directly) I added default values like: $build = array().
| Comment | File | Size | Author |
|---|---|---|---|
| ds-adding-hidden-region-and-build-to-code-field-7.x-1.4.patch | 2.36 KB | OnkelTem |
Comments
Comment #1
OnkelTem commentedChanging the title to be more specific.
Comment #2
bones commentedThis is excellent. Just what I was after.
Have tested with 7.x-1.5 and it works great.
My use was actually one of your examples, to wrap a link field around an image field.
Please include in next release.
Thank you!
Comment #3
swentel commentedCommitted and pushed to both branches. It's an 'Extras' thing though, so you need to enable this. A default hidden region was very confusing during our tests.
Comment #4
swentel commentedComment #5.0
(not verified) commentedp.s.