pepebe
2/9/2016 - 5:44 PM

MODX Plugin (OnDocFormSave): Extract Teaser Layouts – saves a specific ContentBlocks layout into a TV to make it available elsewhere. To pre

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``]]

<?php
// 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)) {
        $ContentBlocks->setResource($resource);
        $html = $ContentBlocks->generateHtml($teasers, array('render_teaser' => '1'));
    }
    $resource->setTVValue('teaser-layouts', $html);

// save resource    
    $resource->save();
    
return;