Silverstripe: GridField in a DataExtension helper

If you've hit the "ManyManyList::add() can't be called until a foreign ID is set" error when hacking away at a Silverstripe 3 GridField implementation that includes a DataExtension, you may find this little nugget helpful.

Very simple when you think about it:

Say you have this extension, which is a basic testimonials extension I knocked up. It uses GridFieldRelationHandler (note the patch info).

class TestimonialPageExtension extends DataExtension {
public static $extraStatics = array(
'belongs_many_many' => array(
'Testimonials' => 'Testimonial',
),
);

public function updateCmsFields(Fieldlist $fields) {
$config = GridFieldConfig_RecordEditor::create();
$list = new ManyManyList('Testimonial','Testimonial_Pages', 'TestimonialID', 'PageID');
$list->forForeignID($this->owner->ID);
$testimonials = GridField::create(
'Testimonials',
FALSE,
$list,
$config
);
//many-many relations
$config->addComponent(new GridFieldManyRelationHandler(), 'GridFieldPaginator');
$columns = $config->getComponentByType('GridFieldDataColumns');
$columns->setDisplayFields(array(
'Title' => 'Title',
'Project' => 'For',
'IsPublic' => 'Public',
));
$fields->addFieldsToTab("Root.Testimonials",
array(
$testimonials
)
);
}
}


.. and you have this Testimonial on the other side of the relation:
class Testimonial extends DataObject {
static $db = array(
'Title' => 'Varchar(255)',
'Content' => 'HTMLText',
'Project' => 'Varchar(255)',
'IsPublic' => 'Boolean',
);

static $many_many = array(
'Pages' => 'Page',
);

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

$datetime = new DateField('DateTime', 'Date');
$datetime->setConfig('showcalendar', TRUE);

$fields->addFieldToTab('Root.Main', $datetime, 'FromPersonName');

return $fields;
}
}


... and the extension is enabled in the usual SS way:
Object::add_extension('Page', 'TestimonialPageExtension');

Saving it will result in the "ManyManyList::add() can't be called until a foreign ID is set" error appearing. To set that foreign ID from within a DataExtension:
		$list = new ManyManyList('Testimonial','Testimonial_Pages', 'TestimonialID', 'PageID');
//the owner ID is the foreign ID
$list->forForeignID($this->owner->ID);

Hopefully that should save you SS hackers some time ;)

Post your comment

Comments

No one has commented on this page yet.

RSS feed for comments on this page | RSS feed for all comments