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.

We're retiring the forums!

The SilverStripe forums have passed their heyday. They'll stick around, but will be read only. We'd encourage you to get involved in the community via the following channels instead:

General Questions /

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

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

[Solved] Display the values of a CheckboxSetField in a template?


Go to End


3 Posts   1636 Views

Avatar
tonito

Community Member, 24 Posts

24 August 2010 at 3:54pm

Edited: 29/08/2010 2:27pm

Can anyone please help? I created a CheckboxSetField following the documentation, but I couldn't figure out in neither the forum or documentation how to display the result:

$Topics returns 1, 2 (etc)

<% control Topics %>
$Topics
<% end_if %>

returns a blank

and
<% control Topics %>
<ul>
<% if 1 %><li>Technology</li><% end_if %>
<% if 2 %><li>Gardening</li><% end_if %>
<% if 3 %><li>Cooking</li><% end_if %>
<% if 4 %><li>Sports</li><% end_if %>
</ul>
<% end_control %>

Returns
- Technology
- Gardening
- Cooking
- Sports

whatever is checked.

Do I need to write a controller?

Here the code that I used:

static $db = array(
'Topics' => 'Varchar',
);

and

function getCMSFields() {
$fields = parent::getCMSFields();

$fields->addFieldsToTab(
'Root.Content.Main',
array(
new CheckboxSetField(
$name = "Topics",
$title = "I am interested in the following topics",
$source = array(
"1" => "Technology",
"2" => "Gardening",
"3" => "Cooking",
"4" => "Sports"
),
$value = "1"
)
)
);
return $fields;
}
}

Avatar
Willr

Forum Moderator, 5523 Posts

24 August 2010 at 8:12pm

Because you have stored the value as a varchar it stores it as a string (as per your output). I thought it exploded this automatically (so you could control over it) but it must not. Therefore you will need a function like this to be able to iterate over the values. Put this in the same object you have the $db

function ExplodedTopics() {
		$set = new DataObjectSet();
		
		if($topics = $this->Topics) {
			foreach(explode(',',$topics) as $key => $value) {
				$set->push(new ArrayData(array('Value' => $value)));
			}
		}

return $set;
}

That will give you an object which you can iterate over like <% control ExplodedTopics %> $Value <% end_control %>. By doing this also you could also move all the <% if 1.. %> logic into the PHP. Eg store the mapping of value = topic (if its not already) in the code so you can reuse it.

Avatar
tonito

Community Member, 24 Posts

29 August 2010 at 2:27pm

Thank you! This is what I needed.