Creating subclasses for mainclass referenced bei has_many

silverstripe-4
Tags: #<Tag:0x00007f10c9671840>

#1

**Silverstripe Version: 4 **

Question: Is it possible to select and create a subclass object for a referenced has_many collection

I have created a page MyPage with a has_many collection:

class MyPage extends Page {
	private static $has_many = [ 
			'Vehicles' => Vehicle::class
	];
	public function getCMSFields() {
		$fields = parent::getCMSFields ();
		$fields->removeByName('Content');
		$fields->addFieldToTab ( 'Root.Vehicles', $grid = new GridField ( 'Vehicles', 'Vehicles to drive', $this->Vehicles(), GridFieldConfig_RecordEditor::create() ) );
		return $fields;
	}
}

The Vehicle class has subclasses Car, Bike and Train.

class Vehicle extends DataObject {
	private static $db = [ 
		'wheels' => 'Int'
	];
}

class Car extends Vehicle {

}

class Bike extends Vehicle {

}

class Train extends Vehicle {

}

I try to add a DropdownField to select and add the subclass to MyPage but it doesn’t work. The GridFieldAddNewButton is a link so the selected subclass was not submitted and a instance of Vehicle was created.
My second try was to extend the Vehicle CMSFields to select the subclass and create the object when the add button is pressed. But how can I change the class to create?


#2

This package works quite well for what you want

See GridFieldAddNewMultiClass


#3

Thanks works perfect.