Martin Rázus
Martin Rázus

Reputation: 4705

CMS Field for many_many relation in SilverStripe 4

I have relation between BlogArticle and BlogCategory many_many & belongs_many_many. I would like to add CheckboxSetField or ListBoxField to cmsFields on BlogArticle, which contains BlogCategories.

Following code shows correct checkboxes in cms, but from some reason it doesn't store the values:

class BlogCategory extends DataObject
{
    private static $db = [
        'Title' => 'Varchar(255)'
    ];

    private static $belongs_many_many = [
        'BlogArticles' => BlogArticle::class
    ];
}


class BlogArticle extends Page
{
    private static $many_many = [
        "BlogCategories" => BlogCategory::class,
    ];

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

        $field = CheckboxSetField::create(
            'BlogCategories',
            'Categories',
            BlogCategory::get()
        );

        $fields->add($field);
        return $fields;
    }
}

Any ideas what's wrong? Thanks a lot!

Upvotes: 1

Views: 199

Answers (1)

ifusion
ifusion

Reputation: 2233

On your BlogArticle.php you aren’t referencing the relationship so it can’t save.

So BlogCategory::get() should be $this->BlogCategories() - you will probably have to map() the values aswell.

There’s an example of using the checkbox field with a $many_many here: https://www.silverstripe.org/learn/lessons/v4/working-with-data-relationships-many-many-1

Upvotes: 1

Related Questions