Creating MODX Articles in Code II

Creating a blog Article using a MODX chunk for the content


In the previous article, we looked at how create Articles resources in code. In this one, we'll see how to set the content of those resources using a MODX chunk.


MODX logo

Using a Chunk

As we saw in the previous article the Article resource must have the class_key field set to Article, and the parent must be the ID of an Articles Container resource. Beyond that, you're free to set (or not set) and resource fields listed on this page, except the id field.

Here's an example that sets the content field using a chunk:

/* Article Creation Code */

/* Set this to the ID of the Articles Container resource  */
$parent = 12;

/* Set this to the ID of an Article template
    (*not* the Article container template) */
$template = 122; set to the ID of the Articles Template.

/* Set this to the ID of the page creator */
$creator = 1;

$pagetitle = 'Some Pagetitle';
$alias = 'some-pagetitle';


$doc = $modx->newObject('modResource');
$doc->set('class_key', 'Article');
$doc->set('parent', $parent);
$doc->set('pagetitle', $pagetitle);
$doc->set('template', $template);
$doc->set('alias', $alias);
$doc->set('createdon', time());
$doc->set('published', $published);

/* Set publishedon field if published */
if ($published) {
    $doc->set('publishedon', time());
}

$doc->setContent($modx->getChunk('SomeChunkName');

$doc->save();

MODX will get the content of the chunk and place it in the content field of the Article resource.


Tags in the Chunk?

You might wonder what will happen if there are tags in the chunk. They will be placed in the content field unchanged. MODX will parse and replace them when the resource is rendered for the browser. There might be cases, though, where you have placeholders in the chunk that you want to replace immediately. We'll see how to do that in the next article.


Coming Up

In the next article, we'll look at how to set the content of your Article resource using a chunk and replace selected placeholders in the chunk during the process.



For more information on how to use MODX to create a web site, see my web site Bob's Guides, or better yet, buy my book: MODX: The Official Guide.

Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)



Comments (0)


Please login to comment.

  (Login)