Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Programatically count checkboxes checked in back-end


Reply


4 Posts   660 Views

Avatar
bostonmark

Community Member, 10 Posts

12 September 2011 at 5:38am

I have about 45 checkbox fields in a new tab in the back-end. I want to show something on the front-end template that says x of 45 checked. How can I programatically determine this in the PHP class to I can pass the checked count and total count to the template?

Avatar
danzzz

Community Member, 175 Posts

12 September 2011 at 8:43pm

hi bostonmark,

how do you manage this checkboxes?
did you extended "Page" or a special page-type with 45 boolean fields or do you use a own dataobject for the possible checkboxes?

Avatar
bostonmark

Community Member, 10 Posts

13 September 2011 at 11:11am

I extended Page and added 45 checkbox fields to it. I may add more later too.

Avatar
danzzz

Community Member, 175 Posts

13 September 2011 at 8:55pm

hi,

you better solve this with a dataobject and manage it with modeladmin.
so you can add new checkboxes easy in the backend. and counting is also much easier.

with you current solution
your checkbox fields are columns in the Page table now. but there are also other columns of course.
you have to find a way to count the relevant fields with value = 1.

a solution may is to use the information_schema DB of mysql.
you need a nameing convention for the checkbox fields, example:

checkbox_1
checkbox_2
checkbox_3

query to get all relevant fields:

select column_name from information_schema.columns where table_name = 'Page' and column_name like 'checkbox_%'

so you get a result with all checkbox_* fields. save the count of rows in a variable ($count_rows_checkboxes) and loop
through the results and create this string:

checkbox_1 = 1 OR checkbox_1 = 1 OR checkbox_3 = 1 // $filter

then create this funciton in Page.php, in the Controller:

public function getCheckboxCount() {

$Count = DataObject::get('Page',$filer); // $filter = string created above
return $Count->Count()." of ".$count_rows_checkboxes." checked.";

}

Then in your Template just call

$getCheckboxCount

I dont tested this, but should work ...