MODX Community

Static elements and setContent

Hello,

I’ve been playing with modX and searching for a workflow that i find nice to work with.
I also like using my IDE instead of the manager so i took a look at static elements
and those work great when created in the manager.

Even better would be creating elements automaticaly from the file system. So i dont need the manager
at all if i quickly want to make another chunk/snippet.
I’ve found ElementHelper for that but couldn’t get it to work perfectly ( maybe it’s too old).

So i took a look at the ElementHelper and kinda made my own plugin that adds templates/snippets/plugins and chunks to modX if they exist in the filesystem but not in the database.
( Plugin runs on OnManagerPageInit and OnWebPageInit )

Everything works fine and the (ie) chunk is created, made static with correct path etc.
But the content doesnt show up initially. I still have to go to the created chunk in the manager, and hit the save button for it to show up and have a proper working static element.

For setting the content i use $element->setContent($content); and $element->save(); element being $element = $this->modx->newObject('modChunk'); But i guess that is not working…

Could someone tell me if i am missing something?

TLDR: Programatically added static elements don’t ‘sync’ content till i hit save in the manager.

edit: Nice site overhaul btw :slight_smile:

Maybe you just have to clear the cache after you saved the new chunk.

$this->modx->cacheManager->refresh();

You could check the database table modx_site_htmlsnippets to see if all the fields (especially snippet) are filled correctly after your plugin ran.

I have only tinkered with it so far, but you might want to take a look at @markh’s Gitify. http://modmore.github.io/Gitify/

I am already clearing the cache after the save() so i dont think it’s an issue with the cache. I also checked the fields in the database and they indeed stay empty. I also tried to filll sippet field with $element->set('snippet',$content); but that didn’t do much either.

I think that after the save() the element somehow finds out it’s an static element and removes the content, pulling it in from the file with some other function… if that makes sense

@andytough yeah i looked at it quite briefly, but maybe i have to try it myself.

Thanks for the suggestions

Looking at the code, it seems that right in the save()-function it tries to read the content from the file, if something changes. So you probably don’t have to set the content yourself, just set the file-path and the source correctly and static to true.

$element = $modx->newObject('modChunk');
$element->set('name','mynewchunk');
$element->set('static',true);
$element->set('static_file', 'path/to/chunk.txt');
$element->set('source', '1');
$element->save();

Thanks for pointing that out! I will tinker some more to see if i can get it to work when i have the time.

Sorry for the late reply, i was on a holiday.

Cheers.