Currently, the field formatter for Field Collections always returns something. When a collection is empty, the formatters either return only the "add" link, when the user is allowed to add a item) or, worse, an empty element with an #attached property.

From the formatter consumer perspective, there is always something to display for a field collection. So when the field's configuration display its label, it will be displayed above or inline of an invisible content.

The behavior for most formatters is to display nothing (no label) for empty fields. Field Collection should cleanly return nothing for empty fields when the user cannot add an item and/or provide a setting to force hiding empty collections.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

pbuyle’s picture

Status: Active » Needs review
FileSize
1.91 KB

The attached patch provides the second option.

BenK’s picture

Subscribing... this would be a nice feature.

RobW’s picture

Great usability/conformity catch, testing the patch now.

sachbearbeiter’s picture

sub

tim.plunkett’s picture

Status: Needs review » Needs work

One small nitpick. Otherwise, I think this is reasonable.

+++ b/field_collection.moduleundefined
@@ -700,6 +702,12 @@ function field_collection_field_formatter_settings_form($field, $instance, $view
+      '#title' => t('Hide empty collection.'),

Checkboxes shouldn't end in full stops

amandine_m’s picture

Suscribe

rp7’s picture

subscribe

pbuyle’s picture

Status: Needs work » Needs review
FileSize
2 KB

Here is a re-roll of the patch.

marvix’s picture

did this worked for any, for me the label still showing when there is no field value!!

pbuyle’s picture

@marvix When a new node with a Field collection field is displayed, the $items argument passed to field_collection_field_formatter_view() contains a empty element instead of being empty. Once the node is edited, the $items argument is an empty array. Tha attached patch now support both cases.

marvix’s picture

did not worked !

rootical’s picture

This one doesn`t work.

dgorton’s picture

Status: Needs review » Reviewed & tested by the community

Works for me - but it took forever to find the checkbox you need to check. Just in case this helps others - the final step after applying the patch is to go to the display settings page on your content type:
admin/structure/types/manage/YOUR_CONTENT_TYPE/display

Then, you need to click on the cog on the right-hand side next to the field collection in question. That will open a dialogue with a checkbox: "Hide empty collection - If enabled, nothing will be displayed for an empty collection (not even the add link)."

Works great once the box is checked!

tim.plunkett’s picture

Status: Reviewed & tested by the community » Needs work
+++ b/field_collection.moduleundefined
@@ -801,6 +811,24 @@ function field_collection_field_formatter_view($entity_type, $entity, $field, $i
+    // Chec if we have some items

Missing a k

+++ b/field_collection.moduleundefined
@@ -801,6 +811,24 @@ function field_collection_field_formatter_view($entity_type, $entity, $field, $i
+    if (!empty($items)) {

$items is never null, it will at least be array(), so you can remove this and just use the foreach

+++ b/field_collection.moduleundefined
@@ -801,6 +811,24 @@ function field_collection_field_formatter_view($entity_type, $entity, $field, $i
+      // Search for at least one non empty item

non-empty, and end with a full stop

+++ b/field_collection.moduleundefined
@@ -801,6 +811,24 @@ function field_collection_field_formatter_view($entity_type, $entity, $field, $i
+        if (!empty($items[0]['value'])) {

Why are you bothering with a foreach when you check $items[0] directly?

+++ b/field_collection.moduleundefined
@@ -801,6 +811,24 @@ function field_collection_field_formatter_view($entity_type, $entity, $field, $i
+      return NULL;

NULL is redundant, just return;

I'm not sure this looks right at all. The first thing field_collection_field_formatter_view() does is call field_collection_field_get_entity() on the $item, which this patch completely bypasses.

bsztreha’s picture

Subscribe

zany’s picture

subscribe

rootical’s picture

do not subscribe but use "following" button!

Cyclodex’s picture

The patch works but you are right, there are some unclear and wrong lines.
I am surprised no one fixed these yet.
If I have some time I will try to provide a corrected patch...
I like this feature!

zany’s picture

I added a check for user_is_logged_in() before hiding an empty collection. I want to hide the heading on an empty block, but I want logged in user to be able to use the add/remove-links. Maybe this could be rolled in as an option. I guess the check should be based on permission though.

idflood’s picture

Status: Needs work » Needs review
FileSize
1.65 KB

Here is a new patch based on #10 with the proposed changes in #14. I've completely removed the foreach, the condition looks like this now:

// Don't display anything for an empty collection.
  if (!empty($settings['hide_empty']) && empty($items)) {
    return;
  }

It's working perfectly on my setup, so thanks @mongolito404 and @tim.plunkett : )

hbalagtas’s picture

Title: Completely hide empty field collections » Patch does not work on nested field collections

Hi, I've tried this patch and while it does remove the empty field on a field collection, but if that field collection has another field collection attached to it then the empty collection is there and is saved again.

tim.plunkett’s picture

Title: Patch does not work on nested field collections » Completely hide empty field collections
larowlan’s picture

Status: Needs review » Reviewed & tested by the community

Works a treat. Great work!

andypost’s picture

Status: Reviewed & tested by the community » Needs work

This option make sense only when Add link displayed, Fields Only formater works fine without patch.

The subject mostly caused by $element['#attached'] & suffix/prefix added by field_collection_field_formatter_links()

Also field_collection_field_formatter_settings_summary() should display something about this setting - "Hide empty" for example

jimmynash’s picture

The patch in #20 worked for me when used in conjunction with the patch in http://drupal.org/node/1339868#comment-6000492

klucid’s picture

I have a quick and easy work around for this issue if the patch didn't work for you.

If you make the field within the field collection required, it will not display. If you don't want the field to be required, make sure the field collection itself is not required under you manage fields settings for that content type.

FYI, I think you still need to delete all of the old empty fields after setting it to required.

Hope that helps!

klucid’s picture

Edit: It actually didn't work. I tested a few times, but now it's requiring the field. Sorry to jump the gun.

dman’s picture

#20 works fine, but as zany noted, it also removes the [Add] links if any.

I want :
non-editors to not see any title with no content
editors to see the empty zone with an add link.

The access check in field_collection_field_formatter_links() looks like a lot of work, so I'm not keen to copy it into field_formatter view just to support this logic.

#1157794: Move markup to template files and improve theming in new 2.x branch would mean we could take care of this display logic ourselves.

still needs work. Tricky.

fago’s picture

I agree this option is unnecessary. If the add-link is disabled and there are no collections, this should be what happens anyway. If not, that's the bug that needs to be fixed.

rvilar’s picture

Status: Needs work » Needs review
FileSize
2.99 KB

Here is a patch that works like fago has commentted. I've modified hook_field_formatter_view() function to not attach any information to $elements array if there are any items to display and we haven't access to add new items.

dman’s picture

This *sounds* better, but I can't visually see what's happening by looking at the patch. ( I guess I should build a test)
So it only adds the 'add' link if the user has add rights? Cool.
Do I get a region title too for where the 'add' happens? It was unstated in #28 - so maybe undefined.

if so it's closer to the desired UI.

andypost’s picture

Status: Needs review » Needs work

This patch make more sense.

But more saner way is to remove #suffix/prefix mess if @fago is not oposit

+++ b/field_collection.moduleundefined
@@ -962,15 +966,17 @@ function field_collection_field_formatter_links(&$element, $entity_type, $entity
+  ¶

trailing white-space

+++ b/field_collection.moduleundefined
@@ -962,15 +966,17 @@ function field_collection_field_formatter_links(&$element, $entity_type, $entity
+  ¶

same

30equals’s picture

Status: Needs work » Needs review
FileSize
2.98 KB

Removed trailing whitespaces from patch as git apply was failing with #30.

30equals’s picture

Fyi, i applied the patch, and i really don't see any improvements with my empty field collections in a content type which already had an embedded field collection..? They're still there.

gillarf’s picture

Same here - no change after applying this patch

RobW’s picture

I'm working on a patch that fixes this, among other things, in #1157794: Move markup to template files and improve theming in new 2.x branch. The behavior I have is:

  • No field collection items, and user doesn't have permissions to add a field or operation (add, edit, delete) links are turned off: no markup, empty field, no field label.
  • No field collection items and user does have permission to add a field: field label with add link.
  • Field collection items plus whatever: well obviously there will be a label and markup.

Does that sound right to everyone here?

Also, marked #1621554: Fields rendering empty <div> and #1570836: Only display the wrapper if the field has items and/or links as duplicates of this issue.

dman’s picture

Makes sense!
I know the empty+edit link is a tricky special case, but is certainly the best case needed for a good UI.

gillarf’s picture

@RobW that's exactly right as far as I can see

And a great idea to make a template, especially if you can override the template for each field collection separately. (field-collection--my-field-collection.tpl.php)

RobW’s picture

Template inheritance proposal is here: http://drupal.org/node/1157794#comment-6270780. Field--field-collection is still output by field module, but there are some issues with bundle names and field names being the same that I'm going to try and fix (see the issue mentioned in the next comment after the one I linked to). If you have any theme suggestions (BAM! Drupal pun) or ideas let me know in the other thread.

RobW’s picture

Status: Needs review » Closed (duplicate)

The patch in #1157794: Move markup to template files and improve theming in new 2.x branch is working well, and takes the saner approach of eliminating the suffix and prefix as mentioned above. Is anyone opposed to marking this as a duplicate and moving further work over there?

barraponto’s picture

Status: Closed (duplicate) » Needs review
FileSize
3.54 KB

Since #1157794: Move markup to template files and improve theming in new 2.x branch is meant for Field Collection 7.x-2.x I decided to go forward with the approach in this patch since it fixes a bug right now.
Rerolled against latest EntityAPI-dev, fixed an undefined index warning.

Macronomicus’s picture

Status: Needs review » Reviewed & tested by the community

Yes! Patch in #41 did the trick...
This issue is compounded if you've the collection set to display within a fieldgroup tab, you get an empty tab where you would want no tab, if there is no content.

sachbearbeiter’s picture

in my use case #41 worked - thanks ...

AaronBauman’s picture

#41 worked for me.
Thank you for continuing to pursue a fix on the 1.x branch.

joep.hendrix’s picture

#41 works for me, please commit.
Thanks for the good work!

azinck’s picture

#41 works for me. RTBC

sclsweb’s picture

#41 does not work for me. (Nothing broken but nothing fixed, either -- no apparent change.)

I patched using Field Collection 7.x-1.0-beta5. This is my first time using a patch, so apologies if I should have been using dev(?). Let me know if there is something additional I should do to get the patch working.

My use case is a content type with 3 non-required field collections attached. Each field collection can have unlimited items added.

Desired behavior:

  • Field collections 1 & 2 should display a label if there is an item, or, if they have no items, no label and no markup.
  • Field collection 3 should have no label, or, if it has no items, no label and no markup.
  • All 3 field collections use the same 3 fields (just the labels are different).

If patching does not work out, I could add a separate content type for field collections 1 & 2, but I'm hoping not to have to re-architect content types for something that will probably be fixed in upcoming releases(?). Any advice would be appreciated.

barraponto’s picture

can you please try patching a dev release?

Anonymous’s picture

This is not working for me either. Dev version + #41.

I create a node w/ a field collection and a blank item is inserted for me.

Edit: Sorry, my issue is related to a boolean value on the field collection. If it's not checked, the 'Off' value still loads into the field collection, rendering the item, regardless if the off value is 0. I'm going to look into fixing it through my node fields.

udog’s picture

I have the same issue: Boolean fields are rendered with their default values even though the field collection to which they belong has not been created.

vinmassaro’s picture

Status: Reviewed & tested by the community » Needs work

Patch applies cleanly to against 7.x-1.x-dev but the empty field collection is still there. I resorted to a prerender approach in the meantime:

function hook_node_view($node, $view_mode, $langcode) {  
  if ($node->type == 'my-node-type') {    
    // Hide the field collection if there are no items.
    if (empty($node->field_my_field_name)) {
      $node->content['field_my_field_name']['#access'] = FALSE;
    }
  }
}
jamesgrobertson’s picture

I applied the patch in #41 to the 7.x-1.x-dev branch, and it seems to have solved my problem. I also implemented the hook_field_collection_is_empty_alter() function from #1614578: Allow other modules to determine if collection item is empty, avoid saving empty item or rendering empty collection in a custom module for good measure.

massanishi’s picture

#41 worked hiding on mine. Thanks!

barraponto’s picture

Status: Needs work » Needs review
dalin’s picture

Status: Needs review » Reviewed & tested by the community

#41 works great for me. It seems that some people are having issues with Boolean fields still however that would be a different bug entirely (this will happen if the Boolean field is outside of the field collection as well).

There's one report of things not working:
https://drupal.org/node/1276258#comment-7276424
but there's no further details.

Given that this patch has been around for a year I think it's best to RTBC this. Any edge case configurations could be dealt with in follow-up issues.

Jonah Fenn’s picture

Patch from #41 worked for us. It would be excellent if we could get this patch rolled in to a release.

Thanks for all of your efforts!

zilla’s picture

ditto on fenns above - i stumbled onto this thread while developing a site, there's one field collection item added to a content type and i just noticed this very week when logged in as a test user that "field collection" still shows a label for an empty field collection of any kind, even where user has no ability to add.

Jonah Fenn’s picture

Let me know if there are any additional things we at Oregon State can do to help push this out. If you need more testers I'll see if I can tap deeper into our community here to get some help.

mavimo’s picture

Same patch of #41 but applied to a field_collection with patch from Entity translation support #1344672: Field Collection: Field translation (entity_translation) support. #53.

Drush make:

projects[field_collection][version] = "1.0-beta5"
projects[field_collection][subdir] = "contrib"
projects[field_collection][patch][1344672] = "https://drupal.org/files/field_collection-et-1344672-53.patch"
projects[field_collection][patch][1276258] = "https://drupal.org/files/hide-empty-field-collections-1276258-33_0.patch"

Status: Reviewed & tested by the community » Needs work
t_en’s picture

Status: Needs work » Reviewed & tested by the community

Patch in #41 still applies to 7.x-1x-dev:

Hunk #1 succeeded at 1215 (offset 12 lines).
Hunk #2 succeeded at 1241 (offset 12 lines).
Hunk #3 succeeded at 1265 (offset 12 lines).
Hunk #4 succeeded at 1273 (offset 12 lines).
Hunk #5 succeeded at 1288 (offset 12 lines).
Hunk #6 succeeded at 1601 (offset 12 lines).

The patch works correctly on our Drupal 7.23 (on php 5.3.10). The patch also applies to the stable 7.x-1.0-beta5, and works.

steinmb’s picture

Drupal 7.23 clean install
PHP 5.4.15
Field_collection HEAD, clean install.

Tested with a multivalue field colletion containing a multivalue text field.

With patch applied

<div class="field-collection-container clearfix">
    <div class="field field-name-field-foo field-type-field-collection field-label-hidden">
        <div class="field-items"></div>
    </div>
    <div class="description field-collection-description"></div>
    <ul class="action-links action-links-field-collection-add">
        <li>
            <a href="/uib/prototype/drupal-7.23/field-collection/field-foo/add/node/4?destination=node/4">Add</a>
        </li>
    </ul>
</div>

Does it thing, though do not feel that
<div class="description field-collection-description"></div>
belong there, does not make any sense to me.

With patch applied but field label enabled

<div class="field-collection-container clearfix">
    <div class="field field-name-field-foo field-type-field-collection field-label-above">
        <div class="field-label">
            Foo:&nbsp;
        </div>
        <div class="field-items"></div>
    </div>
    <div class="description field-collection-description"></div>
    <ul class="action-links action-links-field-collection-add">
        <li>
            <a href="/uib/prototype/drupal-7.23/field-collection/field-foo/add/node/4?destination=node/4">Add</a>
        </li>
    </ul>
</div>

Not 100% sure about the end result here. In my mind should field label not be printed if the field is empty. I do not however think this is a reason to keep this from RTBC. The real fix is worked on in #1157794: Move markup to template files and improve theming in new 2.x branch but they introduce to many changes to how this is themed that it will not happen in 7.x-1 but in 7.x-2.

btw: If any of the maintainers are reading this, could you pls open a 7.x-2.x branch?

fago’s picture

Status: Reviewed & tested by the community » Needs work
+++ b/field_collection.module
@@ -1583,7 +1589,7 @@ function field_collection_field_get_entity(&$item, $field_name = NULL) {
+    if (!empty($item['revision_id']) && $entity->revision_id != $item['revision_id']) {

How is that related?

Else #41 looks good.

btw: If any of the maintainers are reading this, could you pls open a 7.x-2.x branch?

Lets' discuss in the respective issue.

barraponto’s picture

Status: Needs work » Needs review
FileSize
3.39 KB

Re-rolled patch without the unrelated fix (left for another issue).

I guess under some circunstances $item['revision_id'] wasn't set and it screamed some issues back at me. Of course, it might be related to the stack at the time (a year ago). In any case, I agree it's unrelated to the current issue.

sydneyshan’s picture

Just tested #64 on a build I'm doing here and it had the desired outcome. Great job, guys!

nadavoid’s picture

Issue summary: View changes
Status: Needs review » Reviewed & tested by the community

Tested and confirmed working as expected.

joep.hendrix’s picture

#64 works, thanks!
I had to manually apply the changes though against the 2013-Oct-10 version.

knalstaaf’s picture

Priority: Normal » Major

Commit this please. It's an ugly issue.

knalstaaf’s picture

Category: Feature request » Bug report

I would rather call it a bug report (considering Drupal standards) than a feature request, but change it back if deemed appropriate.

Hiding a field (collection) when empty shouldn't be something that requires patching (let stand manually, as described in #67). It's expected by default.

bojanz’s picture

#64 works fine on my build as well.

extect’s picture

Working good. Please commit.

FiNeX’s picture

I also confirm patch #64.

betz’s picture

same here, works smoothly.

aasarava’s picture

+1 on #64

jdanthinne’s picture

Please commit #64…

fago’s picture

Status: Reviewed & tested by the community » Fixed

Thanks, committed.

draxxdk’s picture

+1 on #64
Thanks for the patch

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

tuthanh’s picture

#64 patch works for me.

Thanks alot :)

caw67’s picture

patchc #64 works!
why dont you commit it?

gateway69’s picture

Sorry to kick this thread also, but it would be nice to have this committed :)

dman’s picture

Guys, it is committed, March 14, 2014

https://www.drupal.org/commitlog/commit/16250/c05116101a1bb5061047e96b44...

Unfortunately the last stable release on d.o was March 13. So that means that it's only in 7.x-1.x-dev still, not the 'recommended' release.

What you want to ask is "Aren't we due for a new stable release please?"

gateway69’s picture

dman! thanks for pointing that out, but yea pushing some fixed into a stable would be preferred.. thoughts?

BillyTom’s picture

I am using Field Collection 7.x-1.0-beta8 and now no label is beeing shown when I view a node with an empty field collection as an anomymous user. However if I am logged in there is still the label and the "add new" link. I know this is going to confuse the editors.

The patch #64 is supposed to hide the label but not the link, is that correct?

nadavoid’s picture

BillyTom: To remove the "add new" link, there is a setting when configuring the field. Once the link is gone and there is nothing left to display as part of the field, the label should disappear again too.

dman’s picture

OK yay!
With field_collection 7.x-1.0-beta8 Nov 5 out, this issue is actually released!

BillyTom’s picture

@nadavoid: I totally forgot to check the display settings, thanks!

gagarine’s picture

I opened a follow up issue concerning boolean fields #2402511: Hide empty field collections with empty boolean fields

knalstaaf’s picture

I'm afraid this is still an issue with the textarea, created a follow-up as well: #2421501: Label of textarea shows despite textarea being empty

marcmueller’s picture

My temporary solution here:

<script>
    jQuery(document).ready(function(){
        if (!jQuery('.field-collection-container').hasClass('field-item')) {
            jQuery('.field-collection-container').hide();
        }
    });
</script>

Nevermind.

AndraeRay’s picture

This is an update of #90, the html structure seems to have changed.

jQuery('.field-collection-container').each(function(){
  if (jQuery(this).find('.content').children().length < 1){
             jQuery(this).hide();
    }
});

This is my temporary solution.

Initially when the field collection is empty, the label does not show. But once you add a value, save it, and then later remove the value it still shows the label.

I am thinking of doing an unset on pre_save if fields are empty.

AnaSwin’s picture

Hello!
I don't know if it can help now, but I have found an alternative solution with hooks. I use HOOK_preprocess_field and I look for ['element']['#field_type'] === 'field_collection'. If an element of this type have an empty ['element']['#items'], I apply the same parameters than an hidden label : ['element']['#label_display'] to hidden, ['label_hidden'] to true, ['label'] to null and add 'field-label-hidden' to ['classes_array'].

Field Collection Version used : 7.x-1.0-beta12
Drupal Version : 7.53 (yes not updaded yet :p)

I hope it can help someone if the HTML structure have changed! Thanks for your works :)

Good luck!

kosher’s picture

I am using 7.x-1.0-beta12, and I am not seeing an option to remove the label of a field collection if it is empty.

I have looked at the patch, and much of it looks to have been implemented in the beta12 version, but there are some lines of code from the original (pre-patch) that have been changed.

Anyone else having issues? Anyone with a solution?

kosher’s picture

I am trying to use the suggestions in #92.

I have:

function hook_preprocess_field(&$variables) {
	if ($variables['element']['#field_type'] == 'field_collection') {
		if (empty($variables['element']['#items'])) {
			$variables['element']['#label_display'] = 'hidden';
			$variables['label_hidden'] = true;
			$variables['label'] = null;
			array_push($variables['classes_array'], 'field-label-hidden');
		}
	}
}

But it is not working. Any suggestions?

kosher’s picture

I ended up figuring out how to hide the labels for the empty field collections.

This is what I did:

function HOOK_preprocess_field(&$variables) {
	
	// hides the label if the field collection is empty
	if ($variables['element']['#field_type'] == 'field_collection' && $variables['element']['#field_name'] == 'FIELD_NAME') {	

		$collection = field_collection_field_get_entity($variables['element']['#items'][0]);

		if (empty($collection->FIELD_NAME)) {
			$variables['element']['#label_display'] = 'hidden';
			$variables['label_hidden'] = true;
			$variables['label'] = null;
			array_push($variables['classes_array'], 'field-label-hidden');
		}
	}

}