问题
I want to know how to correctly save values selected with a ListboxField.
new ListboxField(
$name = "Categorie",
$title = "Catégorie(s)",
Categories::get()->map('ID','Title'),
$value = 1,
$size = 4,
$multiple = true
);
In my example, I can save more than one category to a $db
field. I am using:
private static $db = array(
'Categorie' => 'Varchar'
);
It works, but when I'm trying to get back categories names into a template it dosen't work at all. The data stored for example is "1,4,9"
.
Is there a better way to store variables from ListboxField?
回答1:
3dgoo is correct that you're probably best using a has_many or many_many relationship here. If for some reason you need to use a single text field, you would just need to manually add a method to your model to look up those related records:
public function getCategories() {
if (empty($this->Categorie)) return null;
return Categories::get()->filter('ID', explode(',', $this->Categorie));
}
You can then do something like the following in your template:
<% loop $Categories %><li>$Title</li><% end_loop %>
回答2:
Use a $many_many
relationship instead of a $db
variable to manage your relationship between your object and Categories
.
private static $many_many = array(
'Categories' => 'Categories'
);
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Main', ListboxField::create(
'Categories',
'Catégories',
Categories::get()->map('ID', 'Title')->toArray(),
1,
4,
true
));
return $fields;
}
来源:https://stackoverflow.com/questions/33130258/silverstripe-3-1-listboxfield-save-array-to-database