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

Note: This information is mainly for MODX Revolution, though much of it also applies to MODX Evolution. The code for getting MODX information in a snippet is mostly Revolution-specific. The various get() methods (with the exception of $modx->getChunk()) are only for MODX Revolution. $modx->makeUrl() and $modx->sendRedirect work in both versions.

Where can I find guidelines for creating a snippet?

There is some good intormation on creating snippets for MODX Revolution here. Most of the information applies to Evolution as well.

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

The current document's ID is available in a MODX Revolution snippet by using
$id = $modx->resource->get('id');

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 tag. 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 tag on the page instead of my snippet's output?

Sometimes, the Rich Text Editor will the text of the document holding the snippet tag. 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 tag. When that happens, MODX won't recognize it as a snippet tag and will just pass it on to the browser for display.

To fix this, edit the document that holds the snippet tag. 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 tag 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.

Another possibilityis that your tag syntax is incorrect. See this page for the proper tag syntax for both MODX Evolution and MODX Revolution.

How can I send information to a snippet?

One way is to send properties in the snippet tag:
[[SnippetName? &size=`tall` &color=`red`]]     
The question mark after the snippet name tells MODX that properties are coming. Each property starts with an ampersand token and its value is surrounded by back-ticks.

Inside the snippet, the properties arrive in the $scriptProperties array:
$shoeSize = $scriptProperties['size'];    
Another way to get the properties is with $modx->getOption():
$showSize = $modx->getOption('size', $scriptProperties, 'large');    
The third argument is optional and provides a default value for use when the property is not set.

Why aren't my snippet properties available in my snippet?

Snippet properties 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 properties 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 strongly recommended that you return a variable or set 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:

MODX Evolution:
Hello [[+firstName+], glad you could make it.
MODX Revolution:
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.

You can also put the placeholder values in an array and send the array as a second argument to $modx->getChunk()
$ph = array(
    'name'=>'Bob'
)
return $modx->getChunk('Greeting', $ph);    

How can I tell if a user is logged in?

There are various methods. One easy method is to use this code:
if ($modx->user->get('username') == '(anonymous)') {
    /* user is not logged in */
}    
Here is the official method for seeing if the user is logged in to the current context:

if ($modx->user->hasSessionContext($modx->context->get('key'))) {
    /* user is logged in */
}    
If you know the name of the current context (e.g., web), you can use this method. The name of the context is required:
if $modx->user->isAuthenticated('web') {
    /* user is logged in to web context */
}    

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

$modx->user->get('username') will get the user name of the currently logged-in user. If no user is logged in, it will return '(anonymous)' — (including the parentheses). For the logged-in user's ID, use $modx->user->get('id').

The method above will get the user's username and id, but almost all the other information about the user is in the User Profile (fullname, email, gender, etc.). You can get it like this (note the capital 'P' in 'Profile'):
$profile = $modx->user->getOne('Profile')
if ($profile) {
    $fullName = $profile->get('fullname');
}    
It's important to make sure the profile exists. If it doesn't, calling its get() method will cause a PHP error.

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 property you need. Then, set those class member variables equal to the properties in the class' init() method (see code in the question below). They will then be available throughout the class's methods/functions as
$this->memberVariable
Here's an example:
class MyClass {
    function __construct($modx, $scriptProperties) {
        $this->modx =& $modx;
        $this->props =& $scriptProperties;
    }
    public function init() {
        $this->size = $this->props['size'];
        $this->color = $this->props['color'];
    }
}    
Now the $modx object is available anywhere in your class with $this->modx and the color value sent in the snippet tag is available anywhere with $this->color.

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->resource object using code like the following:
$title = $modx->resource->get('pagetitle');
The most commonly used object names are: content, pagetitle, longtitle, alias, introtext, description, and menutitle. For a more complete list, look here.

How can my snippet get information about a MODX system setting?

Earlier in this FAQ, we saw $modx->getOption() used to get a snippet property. It is also the preferred method to get System setting values:
$yourVariable = $modx->getOption('setting_name', null);
Look in System | System Settings to see a list of the possible settings. Click on the little plus sign to the left of a Setting to see a description. The following are also available with $modx->getOption() even though they don't appear in the System Settings Table:
site_url
base_path
base_url
core_path
assets_path
assets_url
manager_path
manager_url
processors_path
connectors_path
connectors_url
url_scheme
http_host

Most of the path and url settings in the list above are also set by MODX as constants in this form:
MODX_CORE_PATH
MODX_ASSETS_URL
etc.    

What's with the weird-looking isset() and empty() statements I see in many MODX 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 property, it's good practice to check and handle things either way.

The isset() function checks to see if the property is set and, most of the time, the line can be read this way:
Is the property set? If yes, use it: if no, use the default value;
Example:
$val = isset($color)? $color : 'Red';
Another version of this uses the empty() function to see if the property is set:
$val = empty($property)? $default : $property;
Note that the method described above can give unexpected results in MODX Revolution for existing default properties and properties in attached property sets because, in those cases, isset() will always return true.

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 should I include files in a snippet?

prefix the path with one of the MODX path constants and append the path to the file. Note that all paths in settings end with a trailing slash, so what you add should *not* begin with one.
include MODX_CORE_PATH . 'components/mycomponent/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 one of the MODX URL contants and append the path to the resource. As with paths, the URL constants all end with a trailing slash.
$url = MODX_ASSETS_URL . '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, "", "", "full") 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, "", "", "full");
$modx->sendRedirect($url);
$modx->sendRedirect() will accept any url, so you can also just insert the full URL as the argument, but using the Resource ID is always safer for resources on the site because the ID will never change.

How can a form produced in a snippet submit the form to the current page or another page?

To forward to the current page, have the snippet do this:
$output = '<form action="[[~[[*id]]]]" >';
//etc.
$output .= '</form>';    
return $output;    
(Note: A better method is to put the form in a chunk and use $modx->getChunk() to get the chunk.)

To submit the form to a page with the ID of 12, have the snippet do this:
$output = '<form action="[[~12]]">';
//etc.
$output .= '</form>';    

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?

This will clear and refresh the cache in current versions of MODX Revolution:
    $cm = $modx->getCacheManager();
    $cm->refresh();

Why do I see my snippet tag 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 tag.

On the Document Create/Edit screen for the document containing your snippet tag, 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 tag back to its original form (e.g. restore the [ and ] characters and change any single or multiple &amp;s to a single 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

 

My book, MODX: The Official Guide - Digital Edition is now available here. The paper version of the book may still be available from Amazon.

If you have the book and would like to download the code, you can find it here.

If you have the book and would like to see the updates and corrections page, you can find it here.

MODX: The Official Guide is 772 pages long and goes far beyond this web site in explaining beginning and advanced MODX techniques. It includes detailed information on:

  • Installing MODX
  • How MODX Works
  • Working with MODX resources and Elements
  • Using Git with MODX
  • Using common MODX add-on components like SPForm, Login, getResources, and FormIt
  • MODX security Permissions
  • Customizing the MODX Manager
  • Using Form Customization
  • Creating Transport Packages
  • MODX and xPDO object methods
  • MODX System Events
  • Using PHP with MODX

Go here for more information about the book.

Thank you for visiting BobsGuides.com

  —  Bob Ray