Grid Field Fetching & Storing Data from Multiple Object


#1

Question:
I have used a grid field before for fetching/storing data from single class, Now I need to fetch/store data from two different object in same grid field, is there any way I can fetch & store BlogPost and ArticlePost in same grid field?

 private static $many_many = array(
    'BlogPost' => BlogPost::class,
    'ArticlePost' => ArticlePost::class
    );



new GridField( 'BlogPost', 'Blog Posts', $this->BlogPost(), GridFieldConfig_RelationEditor::create())

#2

The only way I can think of to do this is for BlogPost and ArticlePost to extend from a common ancestor, such as Post. Then you could do something like:

<?php

private static $many_many = [
    'Posts' => Post::class,
];

public function ArticlePosts()
{
    return $this->Posts()->filter([
        'ClassName' => 'ArticlePost'
    ]);
}

public function BlogPosts()
{
    return $this->Posts()->filter([
        'ClassName' => 'BlogPost'
    ]);
}

...

GridField::create(
    'Posts',
    'Blog and Article Posts',
    $this->Posts(),
    GridFieldConfig_RelationEditor::create()
);

There’s a config setting you can use so that Post is treated as an abstract class and isn’t allowed to be created in the CMS, can’t recall what it is off the top of my head though.