Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
MODX Plugin (OnDocFormSave): Extract Teaser Layouts – saves a specific ContentBlocks layout into a TV to make it available elsewhere. To prevent the layout from rendering in the content area you need to wrap your CB layout template into [[+render_teaser:is=`1`:then=`<template here>`:else``]]
// load service
$corePath = $modx->getOption('contentblocks.core_path', null, $modx->getOption('core_path').'components/contentblocks/');
$ContentBlocks = $modx->getService('contentblocks','ContentBlocks', $corePath.'model/contentblocks/');
// get cb json
if ($modx->event->name == 'OnDocFormSave') {
$cbJson = $resource->get('contentblocks');
} else {
$cbJson = $resource->getProperty('content','contentblocks','');
$cbContent = $modx->fromJSON($cbJson);
if (empty($cbContent)) return;
// extract teaser layouts (id: 6)
$teasers = array();
foreach ($cbContent as $i => $layout) {
if ($layout['layout'] == 6) {
// if is teaser layout, save it into a new array
$teasers[] = $layout;
// save to TV as json
//$resource->setTVValue('teaser_json', json_encode($teasers));
// save to TV as HTML
$html = '';
if (!empty($teasers)) {
$html = $ContentBlocks->generateHtml($teasers, array('render_teaser' => '1'));
$resource->setTVValue('teaser-layouts', $html);
// save resource
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment