I would like to be able to show/hide a group of fields (according to the documentation it's supposed to work).

I've created a fieldset with all fields that will be dependent but this group field is not in the list of dependent. How can a dependee affect a group of dependent fields ?

Thanks!

Comments

peterpoe’s picture

Title:Fieldgroup do not appear in the list of dependent» Fieldgroup support
Component:User interface» Compatibility w/ other modules
Category:bug» feature

This functionality is still missing from Conditional Fields 7.x-3.x. Please follow this issue for announcements when it will be implemented.

pgorecki’s picture

subscribe

Martin Mayer’s picture

subscribe

Shadlington’s picture

Subbing

MrPhilbert’s picture

Subbing too.

clashar’s picture

+1

stevebab’s picture

subscribe

thomasringier’s picture

Assigned:Unassigned» thomasringier

subscribe

Shadlington’s picture

I don't think you meant to assign it to you - unless you intend to fix this yourself?

thomasringier’s picture

No, you are right, but can't change it back.

Shadlington’s picture

Assigned:thomasringier» Unassigned

That's because I fixed it for you :)

jackbravo’s picture

subscribe

jackbravo’s picture

I was taking a shot at implementing this and found that under current implementation this seems almost impossible. The conditional_fields table saves only the field id, which is a number. Based on this number there is no way of knowing whether it is a regular field or a group field.

What I think is that in order to implement this the conditional_fields table should change to store the field name instead. Or add another column that specifies if this is a field or a group field.

What do you think?

Also, this only would apply to the dependent field, as no dependee can be a field group.

AtomicTangerine’s picture

sub!!!

Fanaile’s picture

Subscribing;

chalee’s picture

+1 subscribing

restyler’s picture

subscribing

drupov’s picture

subscribe

misxooo’s picture

subscribe

Coupon Code Swap’s picture

+1

this would be very useful.

peterpoe’s picture

Field group support is not a small task, it will probably take some time. In the meantime, consider using the Field collection module, which already works (almost) perfectly with Conditional fields.

#14: You're right, it would be necessary to change the schema by adding a 'dependent_type' or 'dependent_module' column that identifies the type of dependent (field or fieldgroup).

jackbravo’s picture

Wow! I didn't know about field_collection. But looks pretty nice. Hope to try it soon.

vasike’s picture

subscribe.
Field collection it's a good tool, but why should we build new entities when just some grouped fields are needed.
I think this is a very needed feature and more than nice to have.

jaxpax’s picture

+1

Tobias Englert’s picture

sub

that0n3guy’s picture

sub

JordanMagnuson’s picture

+1 For this.

jackbravo’s picture

@davidlerin there is now a follow button at the top you know =)

-ds-’s picture

This feature would be great!

I have a huge form with 100+ fields that are dependent on each other and I would really like to display them using tabs split into their categories etc rather than on one massive long page as not all fields are needed depending on the initial selection.

Rontero’s picture

I found that Conditional Fields module does actually work with Fieldgroup module. I use vertical tabs for sorting all my fields. Unless both dependent and dependee are in the same tab, dependencies work.

mrfelton’s picture

@Rontero - what do you mean 'it works'? Im using Accordion groups to group fields, and these accordion groups not available for selection by conditional fields. Accordian are much the same as vertical tabs in terms of the implementation - it's just a different widget on the fieldgroup. How exactly re you using vertical tabs with conditional fields?

Rontero’s picture

@mrfelton I'm using conditions on fields not on accordions etc. As long as yoour dependent and dependee are in the same group, Conditional Fields module works.

Example from my site:

I have Drupla Commerce installed for adding products to my site.
Case: Select the appropriate country (the manufacturer is based in) after user selects maker's name.

  1. Product group called basic info (type: vertical tab)
    • Field 1: Maker's name (field type: select list)
    • Field 2: Maker's country (field type: select list)

First field is dependee and second is dependent.

After constructing such a form, in manage dependencies tab i made proper dependent/dependee selections and as a rule used fields with a value / has value.

I hope this helps.

Fanaile’s picture

@Rontero;

True, even if the two fields are not in the same field group the dependencies work. For example, one client's site has registrants choose individual or group registration type. If they choose individual several conditional fields will be shown and vice versa if you choose group.

But what he wants and what I'm trying to get working again is that the entire field group will be shown or hidden pending the choice. Otherwise even if I set each field to show or hide pending the choice, the field group still shows - with the label for it - just none of the individual fields do.

bryancasler’s picture

I'm looking for the same solution as Fanaile

Golem07’s picture

@Fanaile: This is exactly what I am in need of, too. Please let us know in case you solve this in any way.

rwilson0429’s picture

Yes, getting the

entire field group will be shown or hidden pending the choice

would be a great feature that's needed.

carlmcdade’s picture

In D7: It would be better to use a parent/child situation. A new field that is the field id of the field_group table as the parent_id. start gathering the children and see if they all have the same parent. if so then show the parent.

The Pixelworx’s picture

Very interested too, has there been any movement on this or will there even be any attempt to implement the feature?

yannickoo’s picture

Oh, no activity here ;(

sg88’s picture

sub

warmth’s picture

Any way to display or not an entire group using CF?

funkytraffic’s picture

+1 subscribing

bitcookie’s picture

For now you can kinda do this with javascript. We haven't tested this too much, but have it running on one of our sites.

First, make a javascript/jquery function to hide empty fieldsets

Drupal.mymodule.cleanupFieldsets = function() {
   
    $("fieldset").each(function(){
      var fieldset = $(this);
     
      fieldset.show();
     
      var wrapper = fieldset.find(".fieldset-wrapper");
      if(wrapper.height() == 0){
        fieldset.hide();
      }
      else{
        fieldset.show();
      }
    });

  }

Then, bind a change event to every form widget in your node form to fire the cleanup function

  $('input, select').change(function(){
    Drupal.mymodule.cleanupFieldsets(); 
  });
friera’s picture

+1

aze2010’s picture

subscribing

mahyarss’s picture

subscribe

i test "field collection" and "fields group" modules with conditional field on profile 2.
but not works

Please support fieldset feature.

miccelito’s picture

@Fanaile #34:

For example, one client's site has registrants choose individual or group registration type. If they choose individual several conditional fields will be shown and vice versa if you choose group.
But what he wants and what I'm trying to get working again is that the entire field group will be shown or hidden pending the choice. Otherwise even if I set each field to show or hide pending the choice, the field group still shows - with the label for it (---)

I have just tested these modules together
Conditional Fields 7.x-3.x-dev
Field collection 7.x-1.0-beta5

in purpose to see if it solves the issue mentioned in this thread with still showing labels for fieldgroups with hidden fields.
And as far I can see from my test, it works!
I did try with fields at admin/config/people/accounts/fields

nevergone’s picture

And since then?

vlooivlerke’s picture

Would it not be better to have conditions for field groups?
Then you can show/hide entire field groups and its fields with 1 simple field condition.

If the field has value then show field group

Maybe this will have to be an add-on module

EDIT:

Wait, I want to hide an empty fieldset if the fields in the fieldset are not visable due to the field condition.

Shiraz Dindar’s picture

hey folks, if you want to show/hide a whole fieldgroup conditionally:

you have to use the hook_field_group_build_pre_render_alter()

Simply :

function your_module_field_group_build_pre_render_alter(&$element) {
  $element['your_field_group']['#states'] = array(
    'visible' => array(
      ':input[name="field_checkbox"]' => array('checked' => TRUE),
    ),
  );
}

This works perfecly. If the group A is in an another group, do this

$element['groupA']['groupB']['#states'] etc....

Courtesy of bobylapointe over at stackpoint.

Works well.

Perhaps conditional fields would implement it as such.

pmichelazzo’s picture

This code didn't work for me. Also I receive this message:

Notice: Undefined index: #id in drupal_process_states() (line 4664 of /Users/me/Sites/tests/includes/common.inc).

ryantollefson’s picture

I finally got this working - similar to #51 & http://drupal.stackexchange.com/questions/14635/hide-a-cck-fieldgroup-us... (but with added if statement to prevent errors I was getting with other modules.

function your_module_field_group_build_pre_render_alter(& $element) {
  if (isset($element['your_field_group'])){
$element['your_field_group']['#states'] = array(
'visible' => array(
'#edit-field-name-und' => array('checked' => TRUE),
)
);
}
}
vlooivlerke’s picture

Issue summary:View changes

Before I try this code, just a stupid question.

Does this code show/hide the fieldgroup using JavaScript in real-time or only after a node save?

And settings like speed and fade options would be a bit more complicated I guess.

ryantollefson’s picture

Does this code show/hide the fieldgroup using JavaScript in real-time or only after a node save?

And settings like speed and fade options would be a bit more complicated I guess.

This shows/hides in real time, but doesn't use javascript, though I'm sure it could be done... perhaps look at: https://drupal.org/node/304255 or http://drupal.stackexchange.com/questions/6960/how-to-add-jquery-plugin-...

arthitst’s picture

+1 subscribing

akolahi’s picture

I'm willing to pay for development of this functionality. Send me a note if interested.

Thanks.

gd1008’s picture

Here is one workaround for this problem that might help someone. I just tested and it worked.

As stated above conditional fields module supports field collections created by Field Collection module, but not field groups created by Field Group module.

Instead of adding field group with a bunch of fields directly to the content type you can add it to a field collection. Then you can apply conditions to that field collection and control visibility of all the field groups and fields inside this field collection.

mastoll’s picture

@gd1008, moving fields from a field group to a field collection does not work if you are using Display Suite for node display. The conditional aspect of the node edit form works fine. The field collection doesn't display in the node view. Have looked at Display Suite and Conditional fields for a solution - none. I don't know where it's easier to address: Field Group, Field Collection, Conditional Fields, or Display Suite. It's a convoluted and interesting interplay between the modules.

rollingnet’s picture

I tried to apply the #51 and #53 patches, but without success.
Can someone confirm that they work and how?

ryantollefson’s picture

These aren't patches, but are meant to be used as a custom module. It's really a work around, but yes it does work just fine.

You should be able to paste the code into "your_module.module". Next rename the field_group and field_name parts to match your actual fields. Then just create "your_module.info", put it all in a folder in your modules directory and enable it.

Either use the code from #51 or #53 (not both).

mauzeh’s picture

#44 does not work for the case of horizontal or vertical tabs. If you want to hide a tab instead of a field group, use this Javascript snippet:

(function($){

  var cleanupFieldsets = function() {

    $("fieldset").each(function(){
      var fieldset = $(this);

      // Find out if the fieldset contains only elements that are hidden,
      // regardless of the fieldset itself being hidden.
      var countShownSubFields = 0;
      $(fieldset).find('div.form-wrapper').each(function(){
        if ($(this).css('display') === 'block'){
          countShownSubFields++;
        }
      });

      var data = fieldset.data();

      // Horizontal tab support
      if (data && data.horizontalTab) {
        if (countShownSubFields === 0) {
          fieldset.data('horizontalTab').item.hide();
        } else {
          fieldset.data('horizontalTab').item.show();
        }
      }

      // Vertical tab support
      if (data && data.verticalTab) {
        if (countShownSubFields === 0) {
          fieldset.data('verticalTab').item.hide();
        } else {
          fieldset.data('verticalTab').item.show();
        }
      }
    });
  }

  $(document).ready(function(){
    cleanupFieldsets();
    $('input, select').change(cleanupFieldsets);
  });

})(jQuery);

apmsooner’s picture

I tried some of the jquery examples above and couldn't get them working for me so I came up with my own implementation that does work and additionally adds prev/next links to navigate through the tabs to combine multi-page functionality with vertical tabs. I still consider myself a jquery novice so I'd sure appreciate any feedback to the below code as if there are ways for better optimization. Functionally... it works quite well though.

(function ($, Drupal) {

    Drupal.behaviors.customNav = {
        attach: function (context, settings) {

            $(".vertical-tabs-pane", context).once('epic').each(function () {
                var fieldset = $(this);
                var countHidden = 0;
                var countVisible = fieldset.find('> div.fieldset-wrapper > div.form-wrapper').length;
                var data = fieldset.data();
                $(fieldset).find('> div.fieldset-wrapper > div.form-wrapper').each(function () {
                    if ($(this).css('display') === 'none') {
                        countHidden++;
                    }
                });
                if (data && data.verticalTab) {
                    if (countHidden === 0 || countHidden !== 0 && countHidden !== countVisible) {
                        fieldset.data('verticalTab').item.show();
                        fieldset.addClass('not-empty').removeClass('empty');
                    } else {
                        fieldset.data('verticalTab').item.hide();
                        fieldset.addClass('empty').removeClass('not-empty');
                    }
                }
                // create navigation dynamically
                $(fieldset).prepend("<div class='form-navigation top clearfix'><a href='javascript:void()' class='prev-tab'>&#171; Previous</a><a href='javascript:void()' class='next-tab'>Next &#187;</a></div>");
                $(fieldset).append("<div class='form-navigation bottom clearfix'><a href='javascript:void()' class='prev-tab'>&#171; Previous</a><a href='javascript:void()' class='next-tab'>Next &#187;</a></div>");
            });

            $('.vertical-tabs-pane.not-empty').each(function () {
                var next = $(this).nextAll('.vertical-tabs-pane.not-empty');
                var prev = $(this).prevAll('.vertical-tabs-pane.not-empty');
                var prevTab = $(this).find('.prev-tab');
                var nextTab = $(this).find('.next-tab');
                if (prev.length === 0) {
                    prevTab.hide();
                } else {
                    prevTab.show();
                }
                if (next.length === 0) {
                    nextTab.hide();
                } else {
                    nextTab.show();
                }
            });
            $('a.next-tab').click(function () {
                var nextTarget = $(this).closest('.vertical-tabs-pane').nextAll('.vertical-tabs-pane.not-empty');
                nextTarget.data('verticalTab').item.find('a').trigger('click');
            });
            $('a.prev-tab').click(function () {
                var prevTarget = $(this).closest('.vertical-tabs-pane').prevAll('.vertical-tabs-pane.not-empty');
                prevTarget.data('verticalTab').item.find('a').trigger('click');
            });

            $('input, select').change(function () {
                cleanup();
                cleanupNav();
            });

            var cleanup = function () {
                $(".vertical-tabs-pane").each(function () {
                    var fieldset = $(this);
                    var countHidden = 0;
                    var countVisible = fieldset.find('> div.fieldset-wrapper > div.form-wrapper').length;
                    var data = fieldset.data();
                    $(fieldset).find('> div.fieldset-wrapper > div.form-wrapper').each(function () {
                        if ($(this).css('display') === 'none') {
                            countHidden++;
                        }
                    });
                    if (data && data.verticalTab) {
                        if (countHidden === 0 || countHidden !== 0 && countHidden !== countVisible) {
                            fieldset.data('verticalTab').item.show();
                            fieldset.addClass('not-empty').removeClass('empty');
                        } else {
                            fieldset.data('verticalTab').item.hide();
                            fieldset.addClass('empty').removeClass('not-empty');
                        }
                    }
                });

            };
            var cleanupNav = function () {
                $('.vertical-tabs-pane.not-empty').each(function () {
                    var next = $(this).nextAll('.vertical-tabs-pane.not-empty');
                    var prev = $(this).prevAll('.vertical-tabs-pane.not-empty');
                    var prevTab = $(this).find('.prev-tab');
                    var nextTab = $(this).find('.next-tab');
                    if (prev.length === 0) {
                        prevTab.hide();
                    } else {
                        prevTab.show();
                    }
                    if (next.length === 0) {
                        nextTab.hide();
                    } else {
                        nextTab.show();
                    }

                });
            };

        }
    };

})(jQuery, Drupal);

Anyone can try this out by pasting the entire script into a .js file loaded in your theme or module or you could just paste it into a rule with the js injector module. I hope someone finds it useful and willing to make it better as it took alot of time for me to research how to do this.
FYI: The main reason why some of the example scripts above weren't working for me is because they were counting .form-wrapper with display:block. This led to inaccurate count for me because .form-wrapper wouldn't be explicitly set with display:block unless conditional fields triggered it so my method is to do a total count of .form-wrapper and compare it to a count of .form-wrapper with display:none. I also had to explicitly look for the first level of .form-wrapper only because in the case of using field collections, there would be several divs within that also had class of .form-wrapper which would totally screw up my count.

apmsooner’s picture

Corrected pasted code in #63 as i had an extra unnecessary div in the selector.

Anybody’s picture

Sadly this important feature is still missing. Is there any work in progress?

apmsooner’s picture

@Anybody,

I think its a little complicated to provide as a fieldset setting as hiding tabs would have to react to field change events and i don't know if a setting like that can account for the specific change events to trigger the function to hide fields unless it provided a field to input selectors that got passed to the javascript. Even so, while my script in #63 works for me, i only accounted for vertical tabs and in my case i only have one level of vertical tabs. If someone put fieldgroups within fieldgroups, i think that could add alot more complexity to try to figure out how to loop through and find hidden fields... and additionally performance could be an issue as number of fields and fieldgroups grow. In the meantime, you could certainly adapt my script above to your needs and get the functionality you need now.

apmsooner’s picture

Technically someone could add a checkbox to the fieldset settings form labeled "Hide hidden fields" that would render a class for the fieldset that could be evaluated in script similar to what i posted but really.... thats not even completely necessary as you can already specify classes to your fieldsets now so you could just change .vertical-tabs-pane in my script to something more generic and that would probably work wouldn't it? You could certainly take out all the navigation stuff from my script and just hide/show fieldgroups on the change events. It actually now makes better sense for me to make my class in the script more generic as there are certain vertical tab groups that i know will always have fields that aren't hidden so no use running the script for nothing.

NancyDru’s picture

The code in #51 and #53 does not work for me (7.28). As a matter of fact, if there is no ID defined in the field settings, it causes several problems.

This would be a great feature to have, but I leave here in 3.5 weeks, so I suspect I'll never see it.

apmsooner’s picture

@NancyDru, why not just do it in jquery? #63 could be modified with conditions to check the type of fieldgroup it is and thus not be specific to vertical tabs. Maybe i'm missing something but i'm not sure i understand the dire need to have it in a module. Just curious.

NancyDru’s picture

A) I am not a javascript person.
B) There is already some code similar to this in their custom module. It just doesn't work.

Grimreaper’s picture

Thanks for code in #63.

imclean’s picture

#51 looks to be on the right track. See also: #1053174: hook_form_alter form state problems

There's some good example code in that other issue. You shouldn't have to write a line of javascript to get this working.

imclean’s picture

For #51 to work and not get the error in #52:

  1. Assign the fieldset an ID, either in "manage fields" or code
  2. Add the class "form-wrapper" to the fieldset, either in "manage fields" or code

Once the above 2 tasks have been completed, you can use something like this example code:

<?php
/**
 * Implements hook_field_group_build_pre_render_alter()
 */
function MY_MODULE_field_group_build_pre_render_alter(&$element) {
 
// Check for your form
 
if ($element['#form_id'] == 'MY_FORM_edit_form') {
   
// Apply state information to fieldsets
   
$element['group_FIELDSET'] += array(
     
// Hide FIELDSET if  CHECKBOX is checked
     
'#states' => array(
       
'visible' => array( 
         
'#edit-field-CHECKBOX' => array('checked' => FALSE),
        )
      )
    );
  }
}
?>
NancyDru’s picture

Ian, a fieldset already has "form-wrapper" and an id. Maybe my problem is that I am triggering on a two-value radio, not a checkbox.

imclean’s picture

NancyDru, maybe it's the base theme we use but our fieldsets don't have an ID or necessary class. Radios should work but you need to use the "value" condition instead of "checked". We use the below method:

<?php
/**
 * Implements hook_field_group_build_pre_render_alter()
 */
function MY_MODULE_field_group_build_pre_render_alter(&$element) {
 
// Check for your form
 
if ($element['#form_id'] == 'MY_FORM_edit_form') {
   
// Apply state information to fieldsets
   
$element['group_FIELDSET'] += array(
     
// Hide FIELDSET if  RADIO option two is selected
     
'#states' => array(
       
'invisible' => array(
         
'#edit-field-RADIO' => array('value' => 'two'),
        )
      )
    );
  }
}
?>

For multiple options (OR):

<?php
/**
 * Implements hook_field_group_build_pre_render_alter()
 */
function MY_MODULE_field_group_build_pre_render_alter(&$element) {
 
// Check for your form
 
if ($element['#form_id'] == 'MY_FORM_edit_form') {
   
// Apply state information to fieldsets
   
$element['group_FIELDSET'] += array(
     
// Hide FIELDSET if  RADIO option two, four or six is selected
     
'#states' => array(
       
'invisible' => array(
         
'#edit-field-RADIO' => array(
            array(
'value' => 'two'),
            array(
'value' => 'four'),
            array(
'value' => 'six),
          ),
        ),
      )
    );
  }
}
?>

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_...

imclean’s picture

Ok I see the potential problem with Conditional Fields.

Multipage Fieldgroup states appear to override the custom states set above. Related fieldgroup issue was marked as a duplicate of this one: #1518026: Support for "Conditional Fields" module, field group remains visible when fields have been hidden using drupal form states.

dnlmzw’s picture

Rewrote some of the code found in example #63, to make it work with horizontal panels. Paste the code into a .js file and load it in your project to make it work. Not well tested, but works for me.

(function ($, Drupal) {
Drupal.behaviors.customNav = {
attach: function (context, settings) {

function cleanUp () {
$(".field-group-htabs-wrapper", context).each(function () {

var wrapper = $(this);
var groupEmpty = true;

$(".horizontal-tabs-pane", wrapper).each(function(){

var fieldset = $(this);
var countHidden = 0;
var countVisible = fieldset.find('> div.fieldset-wrapper > div.form-wrapper').length;
var data = fieldset.data();

$(fieldset).find('> div.fieldset-wrapper > div.form-wrapper').each(function () {
if ($(this).css('display') === 'none') {
countHidden++;
}
});

if (data && data.horizontalTab) {
if (countHidden === 0 || countHidden !== 0 && countHidden !== countVisible) {
groupEmpty = false;
}
}

});

if(groupEmpty) {
wrapper.hide();
} else {
wrapper.show();
}

});
}

cleanUp();

$('input, select').change(cleanUp);
}
};
})(jQuery, Drupal);

benmmc’s picture

I tried others here, but none of them worked, so I wrote this very generic JS that basically looks inside each fieldset for form-item class elements, and determines whether they have been hidden or not. If a fieldset has any non-hidden items, it shows the group. Otherwise, it hides it.

The :not() selector is necessary because some widgets have the form-item class for individual choices, as opposed to one element with the form-item class for each field. I may have missed some widgets, but this selector covered all the widgets I was using.

$('select#edit-field-whatever-und').change(function() {
$('form.node-whatever-form fieldset.fieldset').each(function() {
hide = true;
$(this).find('.form-item:not(.form-type-radio, .form-type-checkbox, .form-type-date-select, .form-type-managed-file, .form-type-date-select .form-type-select)').each(function() {
if($(this).css('display') != 'none'){
hide = false;
}
});
if(hide == true){
$(this).hide();
}else{
$(this).show();
}
});
});
eMuse_be’s picture

subscribe

milos.kroulik’s picture

I tried to apply solution from #78, but it didn't work. Maybe I've done something wrong - is there anyone, who tried it?

tomvv’s picture

#63 is great for hiding of empty tabs, thanks.

System Lord’s picture

+1

eMuse_be’s picture

+1

Parkes Design’s picture

+1

axe312’s picture

Please do not write "+1" to the issue, instead use the "Follow" button on the right upper area of the issue.

Since this issue is needed by so many people, it might be smart to fund some money to fix it? https://www.drupalfund.us/

kitzinger’s picture

+1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1 +1

!!!!!!!!

System Lord’s picture

I have to agree with ktzinger. The "Follow" feature doesn't tell anybody that I'm having similar issue. Maintainers react to volume of concern (issue comments) not to who's following. What if someone commented "I'm having the same issue." Would you tell them to stop posting that and use "Follow" ? In my mind "following" could simply mean a member is curious about a topic and don't have an issue or comment. Which to me means if everyone used "Follow" the maintainers would not have any indication that there is bigger issue than it appears.

I've been wanting to say that for months! :) Thank kitzinger!

apmsooner’s picture

If someone wants to try to create a patch that includes settings that would implement code similar to #63 as a setting.... that would be a big plus and would push this closer to an actual addition to the module. It would of course need to accommodate other types of tabs rather than just vertical but it seems as though it could be a setting added within each field group parent container to hide/show child tabs if fields are hidden.

Otherwise, feel free to use/modify that code for your needs as a workaround. There are several confirmations that it works...

kitzinger’s picture

@apmsooner - yes yes yes we get it, we have read the posts about the code, we can see the code above, but that is not a resolution and not why we are posting. :D We are posting to keep the thread alive so that, hopefully, some day soon, the maintainer or a possible contributor will see our outcries and maybe devote some highly appreciated time to help. Of course they are not obliged, and there is a code posted above, but it would be lovely if the feature was available in the bare module! ... just being a bit cheeky, but nonetheless.....

Hope you are not offended in any way, that is certainly not the intention! Of course I am still very grateful for the module

jlbellido’s picture

Subscribed

bgilhome’s picture

I've implemented an approach to add fieldgroups as a dependent. In the conditional_fields_element_after_build function, as well as any field that is saved as a dependent, any field that is a child of a fieldgroup saved as a dependent also gets the dependency attached. NB currently only includes first-level children.

Tested with 'visible' state but in theory could use other states eg. 'required'.

Also in conditional_fields.js I've added the js from #51/#53 above to hide empty fieldsets on load and form input/select click. Currently only works with field_group display types that output a fieldset tag. This should probably also be extended to bind to input change events, eg. text inputs.

As is, this would probably break if there were field_groups with the same numerical ID as any field IDs. Maybe the 'dependent' column in the conditional_fields table could be changed to VARCHAR and any field group IDs prepended with eg. 'group_'?

The patch also includes the start of another approach using hook_field_group_pre_render_alter that could be used to add states to the fieldset itself (instead of the child elements).

apmsooner’s picture

@bgilhome,

One thing i see with your javascript in that patch is that like some of the other code submitted here:

+      $fieldset.find('.form-wrapper').each(function(){
+        if ($(this).css('display') === 'block'){
+          countShownSubFields++;
+        }
+      });

This assumes the style exists for display:block to get the count however, if there are fields within the fieldset that are not affected by conditional fields, they will not be explicitly set with display:block so your countShownSubFields variable won't include those and thus render the fieldset hidden when it shouldn't be. My code in #63 does a count on hidden and compares to total count to determine if group should hide/show. Also, in cases like field collections, .form-wrapper may exist multiple times within the field so again, my jquery targets with specificity to only count the first instance, otherwise, again your count could get thrown off. Just my $0.02.

bgilhome’s picture

@apmsooner, sure, that js is a little janky - it might be best to use the hook_field_group_pre_render_alter in the patch to add some #states rather than trying to bind to input click/changes and count fields.

bgilhome’s picture

Small fix to set $groups as an empty array if none present in conditional_fields_dependency_add_form.

djween’s picture

Hi,

Thanks for the patch in #94. I received this after I patched...

Notice: Undefined index: dependent in conditional_fields_element_after_build() (line 312 of /xxxx/xxxx/xxxx/xxxx/sites/all/modules/conditional_fields/conditional_fields.module).

Thanks

davidczadilek’s picture

@djween
just patched it myself today and it works just fine
i have a rather complex set up of dependencies by now, so i suppose you either made some mistake while patching or you had a different base
@bgilhome
thanks for the patch. does not work right though

  • only fieldsets are hidden - group fields module also allows divs and other forms of grouping
  • fieldsets with non-hidden "form-wrapper" elements are hidden. addressfield and datefield modules do not have these classes - so they are hidden by default with that patch (#94)

I'm still trying to figure out an alternative way - trying to see how the module shows/hides single fields in the first place - but I havent quite figured it out yet (have only worked with drupal for a few days so far). But if i find a better solution - i'll surely post it.

jrb’s picture

@pmichelazzo
@NancyDru

I was having the same problem as in #52. It wasn't working, and I was getting this notice:

Notice: Undefined index: #id in drupal_process_states() (line 4664 of /includes/common.inc).

The key to fixing it was here:

https://www.drupal.org/node/1053174#comment-9153819

You need to add the #id directly to the fieldgroup array, not as an attribute. Once I did this, it worked as expected.

My function ended up like this:

/**
* Implements hook_field_group_build_pre_render_alter.
*/
function mymodule_field_group_build_pre_render_alter(&$element) {
  if (!empty($element['group_slideshows'])) {
    $element['group_slideshows']['#id'] = 'group-slideshows';
    $element['group_slideshows']['#states'] = array(
      'visible' => array(
        'input[name="field_allow_slideshows[und]"]' => array('checked' => TRUE),
      ),
    );
  }
}
davidczadilek’s picture

Found another Problem - third-level and higher field groups are not hidden (programmatically).
There's already a ticket in the field-group module, but I think it's this module's part to handle this.

I'll leave it for now - maybe using a workaround to have only second level conditional fields, as I currently have no time to look into it more closely.

Some info that's interesting as well - the fields within that displayed third level group (actually all fields from that form) are all hidden per user role/permissions on the path the problem occurs on.

bgilhome’s picture

I've implemented this a different way, patch attached. Instead of showing/hiding empty fieldgroups via JS, I've used the hook_field_group_build_pre_render_alter (which runs after form's after_build is done) to manually call conditional_fields_element_after_build() for any fieldgroup elements and fieldgroup children elements, and conditional_fields_form_after_build() after that.

This way, #states can get appended to the fieldgroup elements themselves, as well as children of fieldgroups. For fieldgroup dependents using visible/hidden states, the #states gets appended to the fieldgroup element. For fieldgroups dependents with other states, the #states get appended to each (first-level) child of the group.

Although the correct #states are appended, currently the show/hide functionality is not working on the fieldgroup element. Not sure if some js needs to be re-attached or something.

This patch relies on a patch to the field_group module to correctly update the #array_parents for each child of a fieldgroup, to include the fieldgroup parent/s: https://www.drupal.org/files/issues/field_group-update_array_parents-249... in https://www.drupal.org/node/2494385
It uses the updated #array_parents when reprocessing elements with conditional_fields_element_after_build() to get the nested form field in conditional_fields_form_after_build(). NB in conditional_fields_attach_dependency() I've set the 'field_parents' and 'parents' keys to #array_parents if available, I couldn't see any reason not to, perhaps someone can tell me!

bgilhome’s picture

StatusFileSize
new10.65 KB