Gallery with many_many relation on image

I am trying to silverstripe framework without cms, have create Gallery model as mentioned below with many_many to Image, Category. And I am able print to count and title of Categories, but with Images returns null; does not print uploaded images .

// model


namespace App\Model;

use SilverStripe\ORM\DataObject;
use SilverStripe\Assets\Image;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\CheckboxSetField;
use SilverStripe\AssetAdmin\Forms\UploadField;
use App\Model\Category;

class Gallery extends DataObject{

    private static $db = [
        'Name' => 'Varchar',
    private static $many_many = [
        'Images' => Image::class,
		'Categories' => Category::class

	private static $table_name = 'Gallery';	
    public function getCMSFields()
        $fields = FieldList::create(
            $uploader = UploadField::create('Images'),
				'Selected categories',


        return $fields;

// template

<h2>Gallery - $Gallery.Name <h2>

$Gallery.Images.Count images<br>
$Gallery.Categories.Count categories<br> 

<% with $Gallery %>	
	<% loop $Images %>
	<% end_loop %>

	<% loop $Categories %>
	<% end_loop %>
<% end_with %>

// controller


namespace App\Control;

use SilverStripe\Control\Controller;
use App\Model\Gallery;
use SilverStripe\Dev\Debug;
use SilverStripe\Dev\Backtrace;

class GalleryController extends Controller{

    private static $allowed_actions = array(

	public function index(){
        return $this->renderWith(array('Gallery', 'Page'));	
	public function Gallery(){
		$gallery = Gallery::get()->first();
		return $gallery;		

	public function Count(){
		$gallery = Gallery::get()->first();
		return $gallery->Images()->count();		

You probably need to add an extension most likely to the image class or extend it so that it states the image belongs_many_many to the Gallery Class.

You should be able to do this with a DataExtension and enable it via your YAML config.

This is 3.x documentation but should still apply.

I figured out that by default the uploaded images are in draft mode, Is there way to make the image public by default.

You can use the $owns directive for that (in your dataobject class):

private static $owns = [

(Don’t forget to run a dev/build)

When you save the dataobject, the related images should be published automatically.

1 Like