Skip to content

Instantly share code, notes, and snippets.

@lozcalver
Created August 15, 2017 13:58
Show Gist options
  • Save lozcalver/1986016320a62db67c9325bfad22d1a2 to your computer and use it in GitHub Desktop.
Save lozcalver/1986016320a62db67c9325bfad22d1a2 to your computer and use it in GitHub Desktop.
Injector:
ManyManyList:
class: MagicManyManyList
<?php
class MagicManyManyList extends ManyManyList
{
/**
* @var array
*/
protected static $join_table_relation_mapping = [];
/**
* Returns the name of the relation being edited
*
* @return string
*/
public function getManagedRelation() {
if (!array_key_exists($this->dataClass, static::$join_table_relation_mapping)) {
static::$join_table_relation_mapping[$this->dataClass] = [];
$obj = singleton($this->dataClass);
$manyMany = $obj->manyMany();
foreach ($manyMany as $relation => $targetClass) {
list($dud, $dud, $dud, $dud, $joinTable) = $obj->manyManyComponent($relation);
static::$join_table_relation_mapping[$this->dataClass][$joinTable] = $relation;
}
}
$map = static::$join_table_relation_mapping[$this->dataClass];
return isset($map[$this->getJoinTable()]) ? $map[$this->getJoinTable()] : '';
}
/**
* {@inheritdoc}
*/
public function add($item, $extraFields = [])
{
$foreignIDs = (array)$this->getForeignID();
$joinTable = $this->getJoinTable();
$relation = $this->getManagedRelation();
// Ensure we have an object to work with
if (is_numeric($item)) {
$item = DataList::create($this->dataClass)->byID($item);
}
if ($item instanceof $this->dataClass) {
$item->extend('onBeforeManyManyRelationAdd', $relation, $foreignIDs, $extraFields, $joinTable);
}
parent::add($item, $extraFields);
if ($item instanceof $this->dataClass) {
$item->extend('onAfterManyManyRelationAdd', $relation, $foreignIDs, $extraFields, $joinTable);
}
}
/**
* {@inheritdoc}
*/
public function removeByID($itemID)
{
parent::removeByID($itemID);
$item = DataList::create($this->dataClass)->byID($itemID);
// Just in case we're given an invalid ID
if (!$item instanceof $this->dataClass) {
return;
}
$foreignIDs = (array)$this->getForeignID();
$joinTable = $this->getJoinTable();
$relation = $this->getManagedRelation();
$item->extend('onAfterManyManyRelationRemove', $relation, $foreignIDs, $joinTable);
}
}
<?php
class MemberExtension extends Extension
{
private static $belongs_many_many = [
'BookedEvents' => 'Event'
];
/**
* @param string $relation
* @param array $foreignIDs
* @param array $extraFields
* @param string $joinTable
*/
public function onBeforeManyManyRelationAdd($relation, array $foreignIDs, array $extraFields, $joinTable)
{
// If this is a new event being added to/removed from the 'BookedEvents' relation...
if ($relation === 'BookedEvents') {
// $eventsJustAdded = Event::get()->byIDs($foreignIDs);
// Do stuff, send notifications, whatever
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment