Skip Navigation

[Resolved] How to count number of selected checkboxes inside a nested repeatable group

This support ticket is created 5 years, 5 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Karachi (GMT+05:00)

This topic contains 15 replies, has 3 voices.

Last updated by ericE-4 5 years, 4 months ago.

Assisted by: Waqar.

Author
Posts
#1312853

I have a repeatable group (Species Calendar) containing a Checkboxes field (24 checkboxes), inside another repeatable group (Fish Species). I'm trying to count the total number if checkboxes that are checked (there will be 24 x the number of Fish Species). I can't find any documentation on this or ideas in the forum. Can you help?

#1312881

Hi Eric,

Thank you for waiting.

To get the count of checked options from a "checkboxes" type field, you can use Types Field API to get the checked values in a string and then convert it into an array to get its count:
( ref: https://toolset.com/documentation/customizing-sites-using-php/functions/#checkboxes )

The custom shortcode for this will look like:
( this code can be added in the active theme's "functions.php" file )


add_shortcode( 'show_count_species_availability', 'show_count_species_availability_func');
function show_count_species_availability_func( $atts ) {
	$atts = shortcode_atts( array(
		'id' => '',
	), $atts );

	// slug of the field
	$field_slug = 'species-availability';

	// getting field's output seperated by ,
	$field_output = types_render_field( $field_slug, array( 'item' => $atts['id'], 'separator' => ',' ) );

	// if there are some values returned, explode the string into array and return the count
	if(!empty($field_output)) {
		$field_output_arr = explode(',', $field_output);
		return count($field_output_arr);		
	}
	else
	{
		// if no checked field values are returned, return 0
		return 0;
	}
}

To show the count in your view, you can pass the target post's ID in this new shortcode like this:


[show_count_species_availability id="[wpv-post-id]"]

I hope this helps and for more personalized assistance around custom code, you can also consider hiring a professional from our list of recommended contractors:
https://toolset.com/contractors/

regards,
Waqar

#1313579

Thanks for this. I need to use the results of the function in a conditional statement to hide or show certain elements. After registered the customshortcode in Toolset -> Settings -> Front-end Content, I tried:

[wpv-conditional if="( '[show_count_species_availability ]' eq '0' )"]<style type="text/css">.uael-rbs-toggle, .uael-rbs-section-2 {display: none !important;}</style>[/wpv-conditional]

But it is always evaluating to zero even when it shouldn't. Am I using the function in the conditional statement incorrectly? It seems to match the documentation (https://toolset.com/documentation/user-guides/conditional-html-output-in-views/using-shortcodes-in-conditions/) and I get the same syntax if I use the "Insert conditional shortcode" GUI.

#1315355

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Eric

Waqar has holidays this week, let me help.

The format for the conditional shortcode looks correct.

You can add an attribute debug="true" to the wpv-conditional shortcode and it will show what is comparing (the left and right sides of the comparison) to help identify any problems.

Instead of putting the shortcode inside a conditional shortcode, I would first simply output it to the screen to see if the results are what you expect.

I've read over the ticket and I suspect there is a problem relating to your nested field groups.

The top-level group is Species Calendar.

This contains nested groups, Fish species, which contains the checkboxes field.

It looks to me like the code Waqar has provided is intended to count the number of checked checkboxes within one Fish species group.

But your intention is to count the total number of checked checkboxes across all the Fish species groups within a single Species Calendar group, is that correct?

If that is the case, the code will need re-thinking, if you could please clarify your intentions first.

#1315877

Hi Nigel,

I added the debug parameter and used the shortcode to display the value from the function, and indeed the function is always evaluating as zero, so you're correct in thinking that the function that Waqar provided is not working correctly.

I can confirm my intention is to count the total number of checked checkboxes across all the Fish species groups within a single Species Calendar group.

#1316205

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Eric

I rewrote the shortcode with the above in mind.

Note that the expected context is that you insert the shortcode when displaying the outer RFG (presumably using a View), and it will then display the count of all of the checked checkboxes in the nested RFGs.

The shortcode takes no arguments and can be used as [checked-count]

You will need to edit/verify the slugs of the nested RFG and of the checkboxes field:

add_shortcode('checked-count', function () {

    global $post;

    // slug of nested RFG
    $nested = 'fishspecies';

    // slug of checkboxes field
    $field = 'species-availability';

    $field = 'wpcf-'.$field;

    // Get the nested RFG posts
    $nested_posts = toolset_get_related_posts( $post->ID, $nested, array(
        'query_by_role' => 'parent',
        'role_to_return' => 'child',
        'limit' => 999,
    ) );

    $checked = 0;
    foreach ($nested_posts as $key => $nested_post) {

        $checkboxes = get_post_meta( $nested_post, $field, true );
        $checkboxes_array = maybe_unserialize( $checkboxes );

        $checked += count( $checkboxes_array );
    }

    return $checked;
});
#1316777

Sorry Nigel, it's still giving a result of zero. Here is the code that I'm using (I edited your code to use the actual name of the nested RFG):

add_shortcode('count-species-availability', function () {
    global $post;
 
    // slug of nested RFG
    $nested = 'species-calendar';
 
    $field = 'wpcf-species-availability';
 
    // Get the nested RFG posts
    $nested_posts = toolset_get_related_posts( $post->ID, $nested, array(
        'query_by_role' => 'parent',
        'role_to_return' => 'child',
        'limit' => 999,
    ) );
 
    $checked = 0;
    foreach ($nested_posts as $key => $nested_post) {
 
        $checkboxes = get_post_meta( $nested_post, $field, true );
        $checkboxes_array = maybe_unserialize( $checkboxes );
 
        $checked += count( $checkboxes_array );
    }
 
    return $checked;
});

And I inserted the shortcode [count-species-availability] in the View that loops the outer RFG (view="fish-species-calendar"). I tested it with the post "Alaska Trophy Adventures Lodge". The count should be 56 for that post. The url of the post is hidden link.

#1316901

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

The parent RFG is species-calendar and the nested RFG is fish-species, is that not right?

You changed the line where the slug of the nested RFG is defined to 'species-calendar', but unless I've misunderstood your set-up it should be fish-species (or whatever the actual slug of the nested RFG is).

I checked this code on my own site before sharing where it worked, so I expect it should work on your site when using the correct slugs, etc.

#1316925
Screenshot 2019-08-15 00.09.46.png

Hi Nigel...no you have it backwards..."fish-species" is the parent and "species-calendar" is the nested child. See attached image. I can also give you access to the admin if that helps.

#1316939

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Ah, okay, I see, in which case I'm not sure why it isn't working.

Yes, can I get access to your site, then, and I will try to debug it.

I will mark your next reply as private so that I can get log-in credentials from you—you may want to create a temporary admin user for me to use that you can later delete. And be sure to have a current backup of your site.

#1317845

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+00:00)

Hi Eric

The problem arises because you insert the shortcode outside of the loop in the View of the outer RFG (fish-species), so the context for counting up the checkboxes inside the nested species-calendar RFGs isn't the current fish-species (which it needs to be), and is instead the post where the View is inserted (e.g. the lodge alaska-trophy-adventures-lodge).

You have the shortcode inside the wpv-items-found section, but not inside the wpv-loop tags, and so the required context is lost.

If you want the sum of all the checked checkboxes in nested species-calendar RFGs summed across all fish-species RFGs rather than for each fish-species group then that's a different task than we've been dealing with so far.

#1318009

Yes that's what I need, it's what I explained back on August 9 when I opened the ticket.

#1319089

Hi Eric,

Thanks for writing back and since Nigel has an off day today, I'll be resuming on this ticket.

I apologize for the confusion earlier, as the shortcode that I shared with you in my first reply was designed to work from the loop of "Species Availability" posts when the ID was provided through the "id" attribute.

The custom shortcode that you and Nigel have been working with would work, if you'll use it inside the loop of nested "Species Calendar" posts.

However, looking at the call of this shortcode in the "Fish Species Calendar" view, I understand, that you'd like to get that count outside the loops for "Species Availability" or "Species Calendar" posts when the scope of the current post is the "Lodges" type post.

For this purpose, you'll need a custom shortcode, that first cycles two nested levels down, and then get the count of the checked field items.


add_shortcode('count-species-availability', function () {
	global $post;

	// slug of level one nested RFG
	$level_one = 'fish-species';

	// slug of level two nested RFG
	$level_two = 'species-calendar';

	$field = 'wpcf-species-availability';

	// Get the nested RFG level one posts
	$nested_level_one_posts = toolset_get_related_posts( $post->ID, $level_one, array(
		'query_by_role' => 'parent',
		'role_to_return' => 'child',
		'limit' => 999,
	) );

	$checked = 0;

	// loop through nested RFG level one posts
	foreach ($nested_level_one_posts as $key => $nested_level_one_post) {

		// Get the nested RFG level two posts
		$nested_level_two_posts = toolset_get_related_posts( $nested_level_one_post, $level_two, array(
			'query_by_role' => 'parent',
			'role_to_return' => 'child',
			'limit' => 999,
		) );

		// loop through nested RFG level two posts
		foreach ($nested_level_two_posts as $key => $nested_level_two_post) {

			$checkboxes = get_post_meta( $nested_level_two_post, $field, true );
			$checkboxes_array = maybe_unserialize( $checkboxes );

			$checked += count( $checkboxes_array );

		}
	}

	return $checked;

I hope this helps.

regards,
Waqar

#1319269

Thanks for this. When I insert the shortcode in my view to just display the result, it works fine--YAY! However, I need to use the results in a conditional statement to hide or show certain elements. After registering the custom shortcode in Toolset -> Settings -> Front-end Content, I tried:

[wpv-conditional if="( '[count_species_availability ]' eq '0' )"]<style type="text/css">.uael-rbs-toggle, .uael-rbs-section-2 {display: none !important;}</style>[/wpv-conditional]

However, even when the shortcode evaluates to a result of zero, the conditional statement is never true. If I add debug="true", the debug information ids also not shown.

Am I using the shortcode in the conditional statement incorrectly? It seems to match the documentation (https://toolset.com/documentation/user-guides/conditional-html-output-in-views/using-shortcodes-in-conditions/) and I get the same syntax if I use the "Insert conditional shortcode" GUI to build the conditional statement.

#1319891

Hi Eric,

Glad that the shortcode works.

I've checked your post "Glacier Bear Lodge" ( hidden link ) and the shortcode does seem to be working in the conditional statement too.
( note: the count of checked items is 0 for this post )

Screenshot: hidden link

The custom CSS code to hide the section is being included in the markup, but it is not applying because other styles which are more specific are overriding it.

You can either make this custom CSS code more specific ( ref: hidden link ) or introduce "!important":


<style type="text/css">.uael-rbs-toggle, .uael-rbs-section-2 {display: none !important;}</style>

regards,
Waqar