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.
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?
How do I get the resource of ID of the current document?
$id = $modx->resource->get('id');
Why doesn't my snippet produce any output?
Why do I see the actual snippet tag on the page instead of my snippet's output?
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?
[[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?
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:
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?
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 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->hasSessionContext($modx->context->get('key'))) { /* user is logged in */ }
if $modx->user->isAuthenticated('web') { /* user is logged in to web context */ }
How can I get information about the currently logged in user?
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?
$this->memberVariableHere'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?
$chunkContents = $modx->getChunk('chunk_name');
How can my snippet get information about the current document?
$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?
$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?
(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]
If that doesn't work, sometimes you need to pass
How should I include files in a snippet?
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?
$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?
$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?
$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?
$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?
$cm = $modx->getCacheManager(); $cm->refresh();
Why do I see my snippet tag on my site instead of the output of the snippet?
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 &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?
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
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