MODx Snippet FAQ
If you don't find an answer here, ask for help in the appropriate section of the MODx Forums. If they might have a bearing on your problem, be sure to include your browser version, MODx version, hosting service, Apache version, PHP version, and MySQL version.
Where can I find guidelines for creating a snippet?
How do I get the resource of ID of the current document?
$id = $modx->documentIdentifier;Note:Do not use:
$id = $modx->getDocumentIdentifier('id');
because it will interfere with using Friendly URLs.
Why doesn't my snippet produce any output?
Why do I see the actual snippet call on the page instead of my snippet's output?
To fix this, edit the document that holds the snippet call. Uncheck the Rich Text checkbox and click on Save. Now you'll be looking at the raw HTML code of the document. Make sure the snippet call shows nothing but the call itself (or paste it in fresh). In the future, either leave the RTE off, or reconfigure the RTE to stop it from translating HTML entities.
Why aren't my snippet parameters available in my snippet?
Can I use echo and print to produce the output of my snippet?
$output=""; $name = "Bob"; $output = "Hello "; // set $output to "Hello " $output .= $name; // tack name onto the end of $output $output .=", glad you could make it."; //add a greeting return $output;For more complex snippets, you should use placeholders for the dynamic content and return a chunk containing those placeholders. Example:
Create a chunk called Greeting that contains the following:
Hello [+firstName+], glad you could make it.Now, in your snippet, just do this:
$name = "Bob";
$modx->setPlaceholder('firstName', $name);
return $modx->getChunk('Greeting');
This separates the logic of your snippet from the presentation.
How can I tell if a user is logged in?
How can I get information about the currently logged in user?
/* See if the page visitor is a logged in web user or manager user */
if (userLoggedIn()) {
$userID = $modx->getLoginUserID();
$userName = $modx->getLoginUserName();
} else {
// Page visitor is not logged in anywhere.
}
How can I access a parameter in the snippet call from inside the snippet.
You can also access the parameters via the associative array $modx->event->params.
$myVariable = $modx->event->params['fileName'];This second method can be useful inside a function. Note that the two methods access separate variables so changes to one won't affect the other. In other words, $filename = 'newFileName'; won't affect the params array member.
Can my snippet use classes?
$this->memberVariable.If you need the $modx object inside class functions, pass it to the class constructor as an argument and set a class member variable to it (e.g. $this->myModx = $modx) in the constructor. It will then be available everywhere in the class as
$this->myModx.
How can I make my classes PHP4 and PHP5 compatible inside a snippet?
class MyClass {
var $myModx;
var $param1;
var $param2;
/* PHP5 Constructor */
function __construct($myModx, $param1, $param2) {
$this->myModx = $myModx;
$this->param1 = $param1;
$this->param2 = $param2;
}
/* PHP4 Constructor */
function MyClass($myModx, $param1, $param2) {
__construct($myModx, $param1, $param2);
}
}
How can my snippet get the contents of a chunk?
$chunkContents = $modx->getChunk('chunk_name');
How can my snippet get information about the current document?
$modx->documentObject['objectName'];The most commonly used object names are: content, pagetitle, longtitle, alias, description, and menutitle. For a more complete list, look here.
How can my snippet get information about a MODx system setting?
$yourVariable = $modx->config['setting_name'];For a fairly complete list of what's available this way, look here under the "Settings" heading.
What's with the weird-looking isset() and empty() statements I see in many snippets?
(expression 1) ? (expression 2) : (expression 3);If (expression1) is true, the code evalates to (expression2), if (expression 1) is false, the code evaluates to (expression 3).
Since the use may or may not have set a particular snippet parameter, it's good practice to check and handle things either way.
The isset() function checks to see if the parameter is set and, most of the time, the line can be read this way:
Is the parameter set? If yes, use it: if no, use the default value;Example:
$val = isset($param)? $param : $default;Another version of this uses the empty() function to see if the parameter is set:
$ val = empty($param)? $default : $param;
Why am I seeing this? "Fatal error: Call to a member function [functionName()] on a non-object in [long path]
global $modx;at the top of the function in order to let PHP know that you mean it to use the $modx object from outside the function rather than creating a new one. If that doesn't work, sometimes you need to pass $modx as an argument to the function containing the code.
How can I tell if the user is viewing the page as a manager?
How should I include files in a snippet?
include $modx->config['base_path'] . 'assets/snippets/mysnippet/myfile.php';That way, the code will work even if it is moved to another server.
How should I reference URLs in a snippet?
$url = $modx->config['base_url'] . 'assets/images/myimage.jpg';That way, the code will still work if you move it to another server.
How can I forward users to another page on the site from my snippet?
$modx->makeUrl($id)where $id is the resource ID of the document you want to send them to. To send users to the document with the ID of 12, for example:
$url = $modx->makeUrl(12); $modx->sendRedirect($url);
How can a form in a snippet forward to the current page or another page?
$output = '<form action="[~[*id*]~]" >'; //etc.To forward to a page with the id of 12, have the snippet do this:
$output = '<form action="[~12~]" >'; //etc.
How can I save a variable in a snippet so other snippets can use it?
$num = 23; $str = 'I'm saving this for use later'; $_SESSION['myNum'] = $num; $_SESSION ['myString'] = $str;In snippet 2:
$num = $_SESSION['myNum']; $str = $_SESSION ['myString'];
When I create a document in my snippet, why can't I see it in the site's menus until I edit it in the Manager?
How can I clear the MODx cache from inside a snippet?
function clearCache() {
include_once "manager/processors/cache_sync.class.processor.php";
$sync = new synccache();
$sync->setCachepath("assets/cache/");
$sync->setReport(true);
$sync->emptyCache();
}
When I cut and paste code from this FAQ, it doesn't always work. Why?
<!-- -->
Why do I see my snippet call on my site instead of the output of the snippet?
I'm getting this error: Parse Error: Syntax Error, unexpected '<'. What does that mean?
What causes this error: Parse error, unexpected T_VARIABLE
- Missing end-of-line semicolon
- Malformed comment or a comment without comment tags
- Missing parentheses around if() statement condition
- Missing one of a pair of parentheses, quotes, braces, or brackets
- Improperly nested parentheses, quotes, braces, or brackets:
if (condition { ( - Space between the "<?" and "php" at the beginning of the snippet
Thank you for visiting BobsGuides.com
— Bob Ray
