SilverStripe 3.1 ListboxField save array to database

假如想象 提交于 2021-02-10 12:38:39

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!