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.


Click on a question to expand the answer

Show All      Hide All

Where can I find guidelines for creating a snippet?

An excellent set of snippet guidelines can be found in the MODx Wiki, here.

How do I get the resource of ID of the current document?

The current document's ID is available in a snippet by using
$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?

Snippet names are case-sensitive. Be sure there is an exact match between the name of the snippet and the name used in the snippet call. That's the most common cause of no output. You may also have an error in your php code (e.g. a missing semicolon at the end of a line) or an error in the html code generated by your snippet.

Why do I see the actual snippet call on the page instead of my snippet's output?

The Rich Text Editor has altered the text of the document holding the snippet call. Depending on the settings, the Rich Text Editor (RTE) will replace some characters with their HTML entities, including the brackets and ampersands in a snippet call. When that happens, MODx won't recognize it as a snippet call and will just pass it on to the browser for display.

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?

Snippet parameters are case-sensitive and should always be enclosed in backticks (`), never single or double quotes. The back tick is usually on the key with the tilde character (~). Failing to use backticks around snippet parameters is, by far, the most common error for beginning snippet developers.

Can I use echo and print to produce the output of my snippet?

Yes, but it's better to use a variable or a placeholder. For a very simple snippet, use a variable (by convention, almost all snippet developers use the variable $output). Put your output in that variable and return it. Example:
$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?

In a snippet, the API function $modx->userLoggedIn() returns true if the user is logged in.

How can I get information about the currently logged in user?

The function $modx->getLoginUserName( ) will get the user's name. The function $modx->getLoginUserID() will return the user's ID. Be sure to use $modx->userLoggedIn() first to make sure that there is a logged in user to check on.
/* 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.

Snippet parameters are available in the snippet code as regular PHP variables. The parameter &`fileName` can be accessed in the snippet as $fileName like any other PHP variable.

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?

Yes. In fact it's the preferred method for all but the simplest snippets. The best method is to declare a class member variable for every snippet parameter you need. Then, set those class member variables equal to the parameters in the class constructor (see code in the question below). They will then be available throughout the class's methods/functions as
$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?

Use two constructor functions like the following:
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?

Use the getChunk() function:
$chunkContents = $modx->getChunk('chunk_name');

How can my snippet get information about the current document?

Information about the current document (the one the snippet is embedded in) is available via the $modx document object using code like the following:
$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?

System setting values are available using this format:
$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?

This is the PHP ternary operator. The form is:
(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]

That usually means the $modx object is not available at that point in your code. If the code is inside a function, you have to put:
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?

The API function isBackend() returns true only if the current page is accessed via the manager.

How should I include files in a snippet?

prefix the path with $modx->config['base_path'] and append the path to the file.
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?

Prefix the URL with $modx->config['base_url'] and append the path to the resource.
$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?

Use $modx->sendRedirect($url). It's best to have MODx generate the URL using
$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?

To forward to the current page, have the snippet do this:
$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?

Use a $_SESSION variable. In snippet 1:
$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?

Usually that's a cache issue. If your menu snippet (usually Wayfinder) is called cached, the menus won't show anything new until the cache is cleared (and it's usually cleared when you edit and save a document). See: 'How can I clear the MODx cache from inside a snippet.

How can I clear the MODx cache from inside a snippet?

Add this function to your snippet and call it to clear the cache:
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?

In order to keep MODx from executing the code, an HTML comment is sometimes inserted in the code. If you cut and paste, you may have to remove those comments:
<!-- -->

Why do I see my snippet call on my site instead of the output of the snippet?

This usually means that you have the Rich Text editor turned on for that document. The editor is trying to be helpful by encoding html entities in the snippet call. On the Document Create/Edit screen for the document containing your snippet call, go to the Page Settings tab an uncheck the "rich text" box. Save the document. Then look at it in the editor. Change the snippet call back to its original form (e.g. restore the [ and ] characters and change & followed by "&" back to just an ampersand. To avoid this in the future if you want to use the Rich Text editor, go to Resources | Manage Resources | Plugins | TinyMCE | Configuration tab. Change "entity encoding" to "raw." Some people also like to disable "cleanup."

I'm getting this error: Parse Error: Syntax Error, unexpected '<'. What does that mean?

Most often, it means you have an extra "<?php" in your snippet code. Sometimes it means you have ">" rather than "->" in a line of code.

What causes this error: Parse error, unexpected T_VARIABLE

There are several causes. Here are the most common:
  • 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