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++]); } } } } } } }
public function blocks(\SS_HTTPRequest $request) { $page = null; /** @var \Page|HasBlocks $page */ if ($pageID = $request->param('PageID')) { $page = \Page::get()->byID($pageID); } else { if ($path = Application::path_for_request($request)) { $page = Application::page_for_path($path); } } if ($page) { if ($page->hasExtension(\Modular\Relationships\HasBlocks::class_name())) { \Director::set_current_page($page); /** @var \GridListBlock $gridList */ if ($gridListBlock = $page->Blocks()->find('ClassName', 'GridListBlock')) { return $gridListBlock->renderWith("GridListItems"); } } } }