Last active
October 4, 2018 09:58
-
-
Save bummzack/de3ebec9859101cfa7506b8fa43b21d8 to your computer and use it in GitHub Desktop.
Properly remove records from localized table once deleted.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Bummzack\Extensions; | |
use SilverStripe\Core\ClassInfo; | |
use SilverStripe\ORM\DataExtension; | |
use SilverStripe\ORM\DataObject; | |
use SilverStripe\ORM\Queries\SQLDelete; | |
use SilverStripe\Versioned\Versioned; | |
use TractorCow\Fluent\Model\Locale; | |
/** | |
* Class FluentCascadeDeleteExtension | |
* | |
* This extension ensures that all localized-entries of a record are deleted, once the main record gets deleted. | |
* This is a workaround/fix for the following issue: https://github.com/tractorcow-farm/silverstripe-fluent/issues/438 | |
* | |
* Apply to the same model as you applied the fluent extension to. Example: | |
* ``` | |
* DNADesign\Elemental\Models\BaseElement: | |
* extensions: | |
* - Bummzack\Extensions\FluentCascadeDeleteExtension | |
* - TractorCow\Fluent\Extension\FluentVersionedExtension | |
* ``` | |
* | |
* This extension works for versioned and unversioned records. | |
* | |
* @package Bummzack\Extensions | |
*/ | |
class FluentCascadeDeleteExtension extends DataExtension | |
{ | |
public function updateDeleteTables(&$queriedTables) | |
{ | |
// Ensure a locale exists | |
$locale = Locale::getCurrentLocale(); | |
if (!$locale) { | |
return; | |
} | |
$localisedTables = $this->owner->getLocalisedTables(); | |
$tableClasses = ClassInfo::ancestry($this->owner, true); | |
// Delete all locale versions | |
foreach ($tableClasses as $class) { | |
// Check main table name | |
$table = DataObject::getSchema()->tableName($class); | |
// If table isn't localised, skip | |
if (!isset($localisedTables[$table])) { | |
continue; | |
} | |
// Remove _Localised record | |
$localisedTable = $this->owner->getLocalisedTable($table); | |
if ($this->owner->hasExtension(Versioned::class) && Versioned::get_stage() == Versioned::LIVE) { | |
$localisedTable .= '_Live'; | |
} | |
$localisedDelete = SQLDelete::create( | |
"\"{$localisedTable}\"", | |
[ | |
'"RecordID"' => $this->owner->ID, | |
] | |
); | |
$localisedDelete->execute(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment