public function onAfterWrite() { parent::onAfterWrite(); if ($this()->hasExtension(HasBlocks::class_name())) { /** @var \ManyManyList $existing */ $existing = $this()->{HasBlocks::relationship_name()}(); if ($this()->{self::SingleFieldName} || $this()->WasNew) { if ($defaultBlockClasses = $this->getDefaultBlockClasses()) { // get class names along with count of each expected $expected = array_count_values($defaultBlockClasses); $sort = $existing->count() + 1; foreach ($expected as $blockClass => $expectedCount) { if (!\ClassInfo::exists($blockClass)) { continue; } $existingCount = $existing->filter('ClassName', $blockClass)->count(); if ($existingCount < $expectedCount) { for ($i = $existingCount; $i < $expectedCount; $i++) { // generate a default title for the block from lang // e.g. ContentBlock.DefaultTitle $templateVars = ['pagetitle' => $this()->{Title::SingleFieldName}, 'singular' => singleton($blockClass)->i18n_singular_name(), 'index' => $i + 1]; // try the block class.DefaultTitle and then Block.DefaultTitle $title = _t("{$blockClass}.DefaultTitle", _t('Block.DefaultTitle', '{pagetitle} {singular} - {index}', $templateVars), $templateVars); /** @var Block $block */ $block = new $blockClass(); $block->update(['Title' => $title]); $block->write(); $existing->add($block, ['Sort' => $sort++]); } } } } } } }
/** * Handles attaching images to the saved block after it has been written if images are allowed. */ public function onAfterWrite() { parent::onAfterWrite(); /** @var Block $block */ if ($block = $this()->Block()) { $request = Controller::curr()->getRequest(); if ($imageIDs = $request->postVar('Images') ? $request->postVar('Images')['Files'] : []) { // TODO may need to fix so handles more than one image (later) if ($block->hasMethod('Image')) { $block->ImageID = reset($imageIDs); $block->write(); } } } }