21492 Posts in 5783 Topics by 2621 members
General Questions
SilverStripe Forums » General Questions » [Solved] Display the values of a CheckboxSetField in a template?
General questions about getting started with SilverStripe that don't fit in any of the categories above.
Moderators: martimiz, Howard, Sean, Ryan M., biapar, Willr, Ingo, swaiba, simon_w
|
Page:
1
|
Go to End | |
| Author | Topic: | 894 Views |
-
[Solved] Display the values of a CheckboxSetField in a template?

24 August 2010 at 3:54pm Last edited: 29 August 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
- Sportswhatever 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;
}
} -
Re: [Solved] Display the values of a CheckboxSetField in a template?

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.
-
Re: [Solved] Display the values of a CheckboxSetField in a template?

29 August 2010 at 2:27pm
Thank you! This is what I needed.
| 894 Views | ||
|
Page:
1
|
Go to Top |


