Create a MODX Content Block template from a specific layout on a resource.

28 September 2020
Read time: 5 mins

Written by:
Graeme Leighfield.

Here's a handy bit of code that should help you out if you want to quickly and easily create a MODX Content Blocks Template from a specific part (layout) of an already created resource.

Want to take a whole page and make it as a template? Heres another top tip blog post for you here that does just that!

Our use case was that we're about to embark on a large website project, that requires a high degree of QC (quality checking), and we needed to create many Content Blocks templates with all there settings and content to adhere to signed off website designs.

By default to make a layout template in content blocks and to ensure its correct, you have to build the layout on a MODX resource, set any settings/content to ensure it's right, then rebuild the entire page in the content blocks template creator.

The new process using the method in this article is simple. Build the layout once - then when happy, use this tool to take it and make it as a template. A much cleaner, and quicker way of doing it! Simply note down the ID of the resource, or the position of the layout in the resource, enter in the ID, then the name of the layout, and press create!

This method will allow you to assign a title, description, and assign it to a category (based upon ones that you've made on your installation of MODX, and create a fully usable template with just one click.

This code is free to use, however please use at your own risk.

OK! Let's get started! Now the form isn't pretty, however it works - we'd recommend this is to be only used by site administrators, and is to be made on a resource that is unpublished (only accessible by site admins!)

Step 1 - Make a chunk called makeCBSectionTemplate with the code below:

[[!makeCBSectionTemplate]]
<h2>Take a page with sections on it, and make a specific section into a MODX Content Blocks Template</h2>
<p>Ensure that the page section is done how you want. Recommend naming the section as it will show up in the list as that name. This will take a specific section, and turn it into a MODX content blocks template</p>
<form action="" method="POST">
    <label>Resource ID:</label><br />
    <input type="number" name="resource_id" value="[[+resource_id]]" /><br /><br />
    [[+sections:isnotempty=`
    <label>Section Name:</label><br />
    <select name="sections">
        [[+sections]]
    </select><br /><br />
    <label>Template Name:</label><br />
    <input type="text" name="template_name" value="" /><br /><br />
    <label>Template Description:</label><br />
    <textarea name="template_description"></textarea><br /><br />
    <label>Template Category:</label><br />
    <select name="category_id">
        <option selected disabled>Select a Category</option>
        [[+cbCats]]
    </select><br /><br />
    <input type="submit" value="Create Section Template" />
    `:default=`<input type="submit" value="Fetch Content Block Sections" />`]]
</form>

Step 2 - Make a snippet called makeCBSectionTemplate with the code below:

<?php
$modx->addPackage('contentblocks', MODX_CORE_PATH . 'components/contentblocks/model/','modx_');
$placeholders = array(
    'resource_id'   => $_POST['resource_id']
);

$resource = $modx->getObject('modResource', $placeholders['resource_id']);

if (!empty($placeholders['resource_id']) && $resource) { //Fetch the CB sections for this resource
    $properties = $resource->get('properties');
    if (!$properties['contentblocks']['content']) {
        return "No Content Blocks properties found against resource ID " . $_POST['resource_id'];
    }
    //Get CB Cats
    $query = $modx->newQuery('cbCategory');
    $query->sortBy('name', 'ASC');
    $cats = $modx->getCollection('cbCategory', $query);
    foreach ($cats as $cat) {
        $placeholders['cbCats'] .= '<option value="' . $cat->get('id') . '">' . $cat->get('name') .'</option>';
    }
    $placeholders['sectionsData'] = json_decode($properties['contentblocks']['content']);
    foreach ($placeholders['sectionsData'] as $key => $v) {
        $title = $v->title;
        if (empty($title)) {
            $layout = $modx->getObject('cbLayout', $v->layout);
            $title = $layout->get('name') . ' - No name set';
        }
        $placeholders['sections'] .= "<option value='" . $key . "'>Position " . $key. ': ' . $title ."</option>";
    }
}
if (!empty($_POST['resource_id']) && strlen($_POST['sections']) > 0) { //Save specific section from resource as template
    foreach ($placeholders['sectionsData'] as $key => $v) {
        if ($key == $_POST['sections']) {
            $template = $modx->newObject('cbTemplate', array(
                'name'         => $_POST['template_name'],
                'description'  => $_POST['template_description'],
                'category'     => $_POST['category_id'],
                'icon'         => 'chunk_B',
                'content'      => '[' . json_encode($v, JSON_UNESCAPED_SLASHES) . ']'
            ));
            if ($template->save()) {
                echo "<h2>Created Template ID " . $template->get('id') . ".</h2>";
                echo "<h3>Taken from MODX Resource ID " . $resource->get('id') . "</h3>";
            } else {
                return "Error saving template";
            }
            break;
        }
    }
}
$modx->setPlaceholders($placeholders, '');

Step 3 - Make the resource.

Make a new resource, and simply call the chunk - I'd ensure that it's not published - As we only want site administrators using this!

On a site with a client that you don't want them accessing this? Then move it into a folder so it's out of sight.

Viola! You're all done!

Load the resource, pop in a resource ID, then press Go. Then, select the layout you need, enter a template name, description and a category and click the button. It's as easy as that! This takes what could take 10-15 minutes of replication, and potential human error, into seconds!

I hope that this helps you out with your MODX content blocks project like it has for us. We love MODX here at GEL Studios - it's our website cms of choice! If you're after some MODX help, be sure to check out our MODX support page.

G


Written by:
Graeme Leighfield.

Share this article:

Read more from us on:

Related articles.

Send us a message.

hello@gelstudios.co.uk

01793 677150

Unit 8, Lancaster Place,
South Marston Park, Swindon, SN3 4UQ