Skip to content

Instantly share code, notes, and snippets.

@mmikkel
Last active June 24, 2019 21:40
Show Gist options
  • Save mmikkel/23910270590aa560604ef3cf2eff0f50 to your computer and use it in GitHub Desktop.
Save mmikkel/23910270590aa560604ef3cf2eff0f50 to your computer and use it in GitHub Desktop.
Fix (hack) for propagating Ether SimpleMap ("Map") elements across all sites in Craft 3
use ether\simplemap\elements\Map as SimpleMapElement;
Event::on(
Elements::class,
Elements::EVENT_AFTER_SAVE_ELEMENT,
function (ElementEvent $event) {
if (!Craft::$app->getIsMultiSite()) {
return;
}
$element = $event->element;
/** @var SimpleMapElement $element */
if ($element->propagating || !$element instanceof SimpleMapElement || !$element->ownerId || !$element->ownerSiteId || !$element->fieldId) {
return;
}
// Unless the element is new, make sure the field is translatable (i.e. we want to propagate updated values)
// Note that we're not actually going the extra mile in accounting for any of the different translation methods, just if it should be propagated or not
if (!$event->isNew && (Craft::$app->getFields()->getFieldById($element->fieldId))->getIsTranslatable()) {
return;
}
$elementsService = Craft::$app->getElements();
/** @var Element $owner */
$owner = $elementsService->getElementById($element->ownerId, null, $element->ownerSiteId);
if (!$owner || $owner->propagating) {
return;
}
// Duplicate the element across the other sites
// Get the sites supported by this element
if (empty($supportedSites = ElementHelper::supportedSitesForElement($element))) {
throw new Exception('All elements must have at least one site associated with them.');
}
// Make sure the element actually supports the site it's being saved in
$siteId = $element->ownerSiteId;
$supportedSites = ArrayHelper::index($supportedSites, 'siteId');
$siteInfo = $supportedSites[(string)$siteId] ?? null;
if ($siteInfo === null) {
return;
}
// Propagate the freshly saved map to all other supported sites
foreach ($supportedSites as $siteInfo) {
if ((string)$siteInfo['siteId'] === (string)$siteId) {
continue;
}
$siteElement = SimpleMapElement::findOne([
'fieldId' => $element->fieldId,
'ownerId' => $owner->id,
'ownerSiteId' => $siteInfo['siteId'],
]);
$siteClone = clone $element;
if ($siteElement) {
$siteClone->id = $siteElement->id;
} else {
$siteClone->id = null;
}
$siteClone->ownerSiteId = $siteInfo['siteId'];
$siteClone->propagating = true;
$elementsService->saveElement($siteClone, false, false);
}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment