Silverstripe Version:
4.2
Question:
I am trying to insert some tags onto pages, I have managed to get the field to appear using:
$fields->addFieldToTab('Root.Main', ListboxField::create( $name = "Tags", $title = "Tag/s", $source = array( "year5" => "Year 5", "year6" => "Year 6", "year7" => "Year 7", "year8" => "Year 8", "year9" => "Year 9", "year10" => "Year 10" )),'Metadata');
but am unsure how to save the information to the database. Once it’s saved I would like to loop over the information in the template and display it as a list on the page.
Sorry if this question has been asked before but I can’t seem to find the answer.
So I finally got this sorted with some help on the Slack board.
I installed GitHub - silverstripe/silverstripe-tagfield: SilverStripe module for editing tags (both in the CMS and other forms)
Then, in the page
use SilverStripe\TagField\StringTagField;
private static $db = [
...
'Tags' => 'Text',
];
public function getCMSFields()
{
$fields = parent::getCMSFields();
...
$fields->addFieldToTab('Root.Main', $field = StringTagField::create(
'Tags',
'Tags',
['Year 5', 'Year 6', 'Year 7', 'Year 8', 'Year 9', 'Year 10'],
explode(',' , $this->Tags)),'Metadata'
);
return $fields;
}
In the controller
use SilverStripe\ORM\ArrayList;
use SilverStripe\View\ArrayData;
public function showTags()
{
$tags = explode(',' , $this->Tags);
$taglist = new ArrayList();
foreach($tags as $item) {
$taglist->push(
new ArrayData(array('tags' => $item))
);
}
return $taglist;
}
and on the template
<% if $Tags %>
<ul>
<% loop $showTags %>
<li>$tags</li>
<% end_loop %>
</ul>
<% end_if %>
I forgot to add that I was using;
private static $db = [
...
'Tags' => 'ListboxField',
];
This is wrong, I changed it to;
'Tags' => 'Varchar',
and now the array is saving to the database…
Now I just need to find out how to loop through it so i can display the items individually, as opposed to looking like [“year6”,“year7”], on the page.