### Install a transport package Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdotransport/xpdotransport.install A basic example showing how to trigger the installation of a transport package. ```php $transport->install(); ``` -------------------------------- ### Start Item Template Example Source: https://docs.modx.com/current/en/extras/wayfinder Example of how &startItemTpl can be used to display a menu start item. ```html [+wf.wrapper+] ``` -------------------------------- ### Setup options script setup.options.php Source: https://docs.modx.com/current/en/extending-modx/tutorials/developing-an-extra/part-3 A PHP script that returns HTML to be displayed during the package installation process. ```php Doodles Installer

Thanks for installing Doodles! Please review the setup options below before proceeding.


'; break; case xPDOTransport::ACTION_UPGRADE: case xPDOTransport::ACTION_UNINSTALL: break; } return $output; ``` -------------------------------- ### Define Setup Options Form Source: https://docs.modx.com/current/en/extending-modx/transport-packages/build-script Create a setup.options.php file to generate a dynamic HTML form for user input during package installation or upgrade. ```php 'my@emailhere.com', 'emailsFrom' => 'my@emailhere.com', 'emailsReplyTo' => 'my@emailhere.com', ); switch ($options[xPDOTransport::PACKAGE_ACTION]) { case xPDOTransport::ACTION_INSTALL: case xPDOTransport::ACTION_UPGRADE: $setting = $modx->getObject('modSystemSetting',array('key' => 'quip.emailsTo')); if ($setting != null) { $values['emailsTo'] = $setting->get('value'); } unset($setting); $setting = $modx->getObject('modSystemSetting',array('key' => 'quip.emailsFrom')); if ($setting != null) { $values['emailsFrom'] = $setting->get('value'); } unset($setting); $setting = $modx->getObject('modSystemSetting',array('key' => 'quip.emailsReplyTo')); if ($setting != null) { $values['emailsReplyTo'] = $setting->get('value'); } unset($setting); break; case xPDOTransport::ACTION_UNINSTALL: break; } $output = '



'; return $output; ``` -------------------------------- ### Get registered startup scripts Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.getregisteredclientstartupscripts Example of retrieving all registered startup scripts into an array. ```php $startupScripts = $modx->getRegisteredClientStartupScripts(); ``` -------------------------------- ### Run New CLI Installation Source: https://docs.modx.com/current/en/getting-started/installation/cli Execute this command from the MODX setup directory to perform a new installation after configuring the XML file. ```bash php ./index.php --installmode=new ``` -------------------------------- ### CLI Usage Example Source: https://docs.modx.com/current/en/extending-modx/xpdo/custom-models/defining-a-schema/upgrade-schema-v1.0-to-v1.1 An example of executing the upgrade script via CLI with multiple arguments. ```bash user@hostname:/home/user/xpdo$ php xpdo/tools/schema/upgrade-mysql-1.1.php --pkg=sample --pkg_path=models/ --schema_name=sample.mysql.schema.xml --schema_path=schemas/ --echo --write --regen ``` -------------------------------- ### Web Request Usage Example Source: https://docs.modx.com/current/en/extending-modx/xpdo/custom-models/defining-a-schema/upgrade-schema-v1.0-to-v1.1 An example URL for executing the upgrade script as a web request. ```http http://localhost/food/xpdo/tools/schema/upgrade-mysql-1.1.php?pkg=sample&pkg_path=models/&schema_name=sample.mysql.schema.xml&schema_path=schemas/&echo=true&write=true®en=true ``` -------------------------------- ### Populating an Object from JSON Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdoobject/field-accessors/fromjson An example demonstrating how to initialize an object's fields using a JSON string and retrieve the values using the get method. ```php $str = '{"name":"Sirius","email":"Black"}'; $object->fromJSON($str); echo $object->get('name').' '.$object->get('email'); // prints "Sirius Black" ``` -------------------------------- ### Example Option Set with Settings Source: https://docs.modx.com/current/en/extras/fred/themer/options/settings A comprehensive example demonstrating various setting types including text, image, file, textarea, select, slider, and a nested CTA group. ```json { "remote": true, "settings": [ { "name": "panel_class", "label": "Panel Classes", "type": "text", "value": "col-6 col-sm-12" }, { "name": "logo", "label": "Logo", "type": "image", "mediaSource": "site-assets", "value": "assets/images/logo.svg" }, { "name": "nda-file", "label": "Upload NDA", "type": "file", "mediaSource": "site-assets-files", "value": "assets/files/contract.pdf" }, { "name": "slogan", "label": "Slogan", "type": "textarea", "value": "Enter your slogan here" }, { "name": "panel_type", "label": "Type of Panel", "type": "select", "options": { "info": "Info Panel", "warn": "Warning Panel", "error": "Error panel" }, "value": "info" }, { "name": "padding_top", "label": "Top padding", "type": "slider", "min": 0, "max": 100, "step": 10, "value": 20 }, { "group": "CTA", "settings": [ { "name": "cta_class", "label": "CTA Class", "type": "select", "options": { "danger": "Red CTA", "info": "Blue CTA", "default": "Default CTA" }, "value": "default" }, { "name": "show_cta", "label": "Show CTA", "type": "toggle", "value": false }, { "name": "color", "label": "Text Color", "type": "colorswatch", "value": "black", "options": [ { "value": "primary", "color": "blue", "label": "Primary" }, "lightcoral", "black", "rgba(0,255,0,.5)" ] }, { "name": "bg_color", "label": "Background COlor", "type": "colorpicker", "value": "white", "showAlpha": true, "options": ["lightcoral", "black", "white"] }, { "name": "page", "label": "Linked Page", "type": "page", "value": { "id": 1, "url": "[[~1]]" } } ] } ] } ``` -------------------------------- ### Get User Settings Example Source: https://docs.modx.com/current/en/extending-modx/core-model/moduser/moduser.getsettings Retrieves all User Settings for the specified user object. ```php $settings = $user->getSettings(); ``` -------------------------------- ### getResources Example Source: https://docs.modx.com/current/en/extras/boilerx/bx-bottom-close An example of using the getResources snippet to fetch resources. ```modx [[getResources@section? &parents=`1316` &context=`extras` &limit=`0` &resources=`1316,[[*id]]` ]] ``` -------------------------------- ### Properties File Example Source: https://docs.modx.com/current/en/extending-modx/xpdo/custom-models/defining-a-schema/upgrade-schema-v1.0-to-v1.1 An example of a PHP properties file used to define arguments for the upgrade script. ```php connect(); ``` -------------------------------- ### xPDO::addPackage with FormIt Example Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdo/xpdo.addpackage An example of loading a specific package (recaptcha) from the FormIt component structure. ```php $xpdo->addPackage('recaptcha', MODX_CORE_PATH.'components/formit/model/'); ``` -------------------------------- ### Placeholder Output Example Source: https://docs.modx.com/current/en/extras/socialsuite/socialsuite.getfacebookprofile The rendered output of the placeholder example. ```html Facebook Name: MODX Likes: 2348 ``` -------------------------------- ### Retrieve a Cache Provider Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdocachemanager/xpdocachemanager.getcacheprovider Example showing how to get a cache manager instance and then retrieve a specific cache provider, such as xPDOMemCache. ```php $cacheManager = $xpdo->getCacheManager(); $provider = $cacheManager->getCacheProvider('xPDOMemCache'); ``` -------------------------------- ### getResourcesTag configuration example Source: https://docs.modx.com/current/en/extras/taglister/taglister.tolinks Example configuration for the target resource to list posts associated with the tags. ```text [[!getResourcesTag? &element=`getResources` &elementClass=`modSnippet` &tpl=`blogPost` &hideContainers=`1` &pageVarKey=`page` &parents=`59` &includeTVs=`1` &includeContent=`1` ]] [[!+page.nav:notempty=` [[!+page.nav]] `]] ``` -------------------------------- ### Install Composer and Gitify Source: https://docs.modx.com/current/en/extras/fred/collab/gitify Commands to install Composer and clone the Gitify repository into the home directory. ```bash cd www; curl http://modx.co/scripts/install.sh | sh mkdir ../gitify; cd ../gitify git clone https://github.com/modmore/Gitify.git ./ ``` -------------------------------- ### Usage Example for @RESOURCE Binding Source: https://docs.modx.com/current/en/building-sites/elements/template-variables/bindings/resource-binding Example showing how to output the contents of a resource with the ID of 12. ```text @RESOURCE 12 ``` -------------------------------- ### Example getResources call Source: https://docs.modx.com/current/en/building-sites/client-proofing/form-customization/rules/tv-default An example of a getResources call used in the context of the documentation. ```text [[getResources@section? &parents=`313` &context=`revolution`]] ``` -------------------------------- ### Example: Display Current User Info Source: https://docs.modx.com/current/en/extras/login/login.profile A complete example showing the snippet call followed by the corresponding placeholders for the logged-in user. ```MODX [[!Profile]]

Username: [[+username]]

Email: [[+email]]

``` -------------------------------- ### Outer Template Example (Evo) Source: https://docs.modx.com/current/en/extras/wayfinder Example of an &outerTpl chunk for Evolution. ```html ``` -------------------------------- ### Example getResources call Source: https://docs.modx.com/current/en/building-sites/client-proofing/form-customization/rules/tab-title An example of a getResources call used in the context of the documentation. ```text [[getResources@section? &parents=`300` &context=`revolution`]] ``` -------------------------------- ### GalleryAlbums containerTpl Example Source: https://docs.modx.com/current/en/extras/gallery/gallery.galleryalbums/containertpl This example demonstrates how to use placeholders to create a navigation interface for gallery albums, including previous/next links and an overview link. ```text [[+nav.curIdx:ne=`
Gallery [[+nav.curIdx]] of [[+nav.count]]
`:else=`
[[+albums]]
`]] ``` -------------------------------- ### Example getResources call Source: https://docs.modx.com/current/en/building-sites/client-proofing/form-customization/rules/tv-title An example of using the getResources snippet to fetch resources with specific parents and context. ```text [[getResources@section? &parents=`314` &context=`revolution`]] ``` -------------------------------- ### Resolve setup-options settings in a PHP resolver Source: https://docs.modx.com/current/en/extending-modx/transport-packages/build-script This script processes setup options during package installation or upgrade by updating system settings. It uses $object->xpdo to access the MODX instance instead of the global $modx variable. ```php xpdo->getObject('modSystemSetting',array('key' => 'quip.emailsTo')); if ($setting != null) { $setting->set('value',$options['emailsTo']); $setting->save(); } else { $object->xpdo->log(xPDO::LOG_LEVEL_ERROR,'[Quip] emailsTo setting could not be found, so the setting could not be changed.'); } /* emailsFrom */ $setting = $object->xpdo->getObject('modSystemSetting',array('key' => 'quip.emailsFrom')); if ($setting != null) { $setting->set('value',$options['emailsFrom']); $setting->save(); } else { $object->xpdo->log(xPDO::LOG_LEVEL_ERROR,'[Quip] emailsFrom setting could not be found, so the setting could not be changed.'); } /* emailsReplyTo */ $setting = $object->xpdo->getObject('modSystemSetting',array('key' => 'quip.emailsReplyTo')); if ($setting != null) { $setting->set('value',$options['emailsReplyTo']); $setting->save(); } else { $object->xpdo->log(xPDO::LOG_LEVEL_ERROR,'[Quip] emailsReplyTo setting could not be found, so the setting could not be changed.'); } $success= true; break; case xPDOTransport::ACTION_UNINSTALL: $success= true; break; } return $success; ``` -------------------------------- ### xPDO::beginTransaction Usage Example Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdo/xpdo.begintransaction A basic example of calling the beginTransaction method on an xPDO instance. ```php $xpdo->beginTransaction(); ``` -------------------------------- ### Default number formatting examples Source: https://docs.modx.com/current/en/extras/socialsuite/socialsuite.prettynumbers Examples showing how various input numbers are transformed by the default prettyNumbers configuration. ```text 5 => 5 515 => 515 5141 => 5.1k 5151 => 5.2k 51415 => 51k 51515 => 52k 515151 => 515k 5151515 => 5.2m 51515151 => 52m 515151515 => 515m 5151515151 => 5.2b 51515151515 => 52b 515151515151 => 515b 5151515151515 => 5,152b 51515151515151 => 51,515b 515151515151515 => 515,152b ``` -------------------------------- ### Simple Example: Chunk and Snippet Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.getchunk A basic example showing a chunk definition and the corresponding snippet call. ```html

Welcome [[+name]]!

``` ```php $output = $modx->getChunk('WelcomeChunk',array( 'name' => 'John', )); return $output; ``` ```html

Welcome John!

``` -------------------------------- ### Move TV to Tab Rule Example Source: https://docs.modx.com/current/en/building-sites/client-proofing/form-customization/rules/move-tv-to-tab An example of using the getResources snippet to target specific parents and context. ```text [[getResources@section? &parents=`1353` &context=`revolution`]] ``` -------------------------------- ### Basic Snippet Code Example for Foreign Databases Source: https://docs.modx.com/current/en/extras/cmpgenerator/cmpgenerator.foreign-databases This example demonstrates how to initialize a new xPDO instance for a foreign database, load a package, and perform basic CRUD operations like creating and retrieving data. ```php getOption('core_path').'config/foreigndb_config.php'; $output = '';// this is what the snippet will return $foreignDB = new xPDO('mysql:host=' . $foreign_database_host.';dbname='.$foreign_database_name/*.';charset='.$foreign_database_charset*/, $foreign_database_username, $foreign_database_password ); $package_path = $modx->getOption('core_path').'components/foreigndb/model/'; // see the scheme file and the xml model element and you will see the attribute package and that must match here // make sure you set the prefix as empty if you don't use it if ( !$foreignDB->addPackage('foreigndb', $package_path, '') ) { return 'Can not load package'; } // lets add some data! // see the scheme file and the xml object element and you will see the attribute class and that must match here $myRow = $foreignDB->newObject('EventName'); $data = array( 'name' => 'MODX Revolution', 'description' => 'A great CMS product...' ); $myRow->fromArray($data); if ( !$myRow->save() ) { $output .= '

Could not create row

'; } else { $output .= '

Created row successfully

'; } // now lets show the data in a quick and dirty table: $output .= ' '; // Note for all HTML you should be using Chunks see: https://docs.modx.org/current/en/building-sites/elements/chunks... /* build query */ $query = $foreignDB->newQuery('EventName'); $rows = $foreignDB->getIterator('EventName', $query); /* iterate */ $list = array(); foreach ($rows as $row) { // from object to array you can also do $row->get('name'); $row_array = $row->toArray(); $output .= ' '; } $output .= '
ID Name Description
'.$row_array['id'].' '.$row_array['name'].' '.$row_array['description'].'
'; return $output; ``` -------------------------------- ### Full Plugin Implementation Example Source: https://docs.modx.com/current/en/extending-modx/plugins/system-events/onloadwebpagecache A complete plugin example that switches on the OnLoadWebPageCache event to modify the pagetitle, a TV value, and the resource content. ```php event->name; switch($eventName) { case 'OnLoadWebPageCache': $modx->event->params['resource']->pagetitle = 'New title'; // меняем значение ТВ $tv = $modx->event->params['resource']->price[1] = '128'; /* // массив значений ТВ array ( 0 => 'name', //название ТВ 1 => 'значение', //значение ТВ 2 => 'default', //параметры вывода ТВ 3 => NULL, 4 => 'text', //тип ТВ ) */ $modx->event->params['resource']->_content = 'New content'.$tv; break; } ``` -------------------------------- ### Example Template Structure Source: https://docs.modx.com/current/en/extras/boilerx This example shows the recommended order for including boilerX chunks within a MODX template. ```text [[$bx-head-open]] [[$bx-head-append]] [[$bx-head-close]] [[$bx-container-open]] [[*content]] [[$bx-container-close]] [[$bx-bottom-open]] [[$bx-bottom-close]] ``` -------------------------------- ### Row Template Example 1 (Revo) Source: https://docs.modx.com/current/en/extras/wayfinder A detailed &rowTpl chunk example for Revolution. ```html [[+wf.linktext]][[+wf.wrapper]] ``` -------------------------------- ### Row Template Example 2 (Revo) Source: https://docs.modx.com/current/en/extras/wayfinder A simple &rowTpl chunk example for Revolution. ```html
  • [[+wf.linktext]] - [[+wf.description]] [[+wf.wrapper]]
  • ``` -------------------------------- ### Row Template Example 1 (Evo) Source: https://docs.modx.com/current/en/extras/wayfinder A detailed &rowTpl chunk example for Evolution. ```html [+wf.linktext+][+wf.wrapper+] ``` -------------------------------- ### Example getResources call Source: https://docs.modx.com/current/en/building-sites/client-proofing/form-customization/rules/field-visible An example of using the getResources snippet to fetch resources from a specific parent and context. ```MODX [[getResources@section? &parents=`124` &context=`revolution`]] ``` -------------------------------- ### Example: Get user comment count Source: https://docs.modx.com/current/en/extras/quip/quip.quipcount Example usage to count comments for the user 'mikegeorge'. ```MODX [[QuipCount? &type=`user` &user=`mikegeorge`]] ``` -------------------------------- ### OnSiteRefresh Plugin Example Source: https://docs.modx.com/current/en/extending-modx/plugins/system-events/onsiterefresh This plugin example logs the cleared cache partitions to the MODX error log when the OnSiteRefresh event is triggered. ```php event->name; switch($eventName) { case 'OnSiteRefresh': $modx->log(modX::LOG_LEVEL_ERROR, 'The cache is cleared '.print_r($partitions)); break; } ``` -------------------------------- ### Object configuration example Source: https://docs.modx.com/current/en/extras/sekformtools/sekformtools.input.autocomplete An example of using the object property to define the data source, sorting, and field mapping for the auto-complete list. ```text [[!input.autocomplete? &object=`{"name": "sekftUSCities", "sortby": "city_name", "value": "city_name", "label": "city_name"}` ]] ``` -------------------------------- ### Initialize build script timer and environment Source: https://docs.modx.com/current/en/extending-modx/transport-packages/build-script Sets up the initial PHP documentation, starts a timer to track build duration, and disables the script timeout limit. ```php newQuery('Box'); $query->rightJoin('Owner','Owner'); $boxes = $xpdo->getCollection('Box',$query); ``` -------------------------------- ### xPDO::commit Usage Example Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdo/xpdo.commit A basic example showing how to call the commit method on an xPDO instance. ```php $xpdo->commit(); ``` -------------------------------- ### Run Basic Upgrade Source: https://docs.modx.com/current/en/getting-started/installation/cli Execute this command from the setup directory to perform a basic upgrade using the configuration defined in your XML file. ```bash php ./index.php --installmode=upgrade ``` -------------------------------- ### xPDO Interaction Example Source: https://docs.modx.com/current/en/extending-modx/xpdo A demonstration of loading a package, managing objects, and querying data with xPDO. This example includes creating a new object, filtering results with xPDOQuery, and iterating through related records. ```php if (!$modx->addPackage('education', '/path/to/model/')) { die('Can\'t load package, try again later.'); } // Get into Harvard (or create a new school with the same name) $school = $modx->getObject('School', ['name' => 'Harvard']); if (!$school) { $school = $modx->newObject('School'); $school->set('name', 'Harvard'); $school->save(); } // Find the 100 students that are alumni and sort by lastname $c = $modx->newQuery('Student'); $c->where([ 'school' => $school->get('id'), 'is_alumni' => true, 'start_year' => $_GET['start_year'] ?? date('Y') - 5, ]); $c->sortby('lastname', 'ASC'); $c->limit(100); foreach ($modx->getIterator('Student', $c) as $student) { echo $student->get('firstname') . ' ' . $student->get('lastname') . ' started studying in ' . $student->get('start_year'); if ($graduation = $student->getOne('Graduation')) { echo ' and graduated in ' . $graduation->get('year') . ".\n"; } else { echo " and has not graduated.\n"; } } ``` -------------------------------- ### Get Debug State Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdo/xpdo.getdebug Example showing how to retrieve the current debug status from an xPDO instance. ```php $isDebugOn = $xpdo->getDebug(); ``` -------------------------------- ### Run a Snippet with Parameters Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.runsnippet Example of executing a snippet named 'Welcome' and passing a 'name' parameter, then outputting the result. ```php $output = $modx->runSnippet('Welcome',array( 'name' => 'John' )); echo $output; // prints 'Welcome John!' ``` -------------------------------- ### Simple cache setting and getting Source: https://docs.modx.com/current/en/extending-modx/caching Demonstrates writing data to the default cache partition with an expiry time and retrieving it. ```php $str = 'My test cached data.'; // Writes the data to the default cache partition with an expiry time of 2 hours. $modx->cacheManager->set('testdata', $str, 7200); // Gets the data from cache again. Returns null if cache is not available or expired. $str = $modx->cacheManager->get('testdata'); ``` -------------------------------- ### Get the MODX Parser object Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.getparser Example showing how to assign the MODX parser instance to a variable. ```php $parser = $modx->getParser(); ``` -------------------------------- ### selfLink snippet call Source: https://docs.modx.com/current/en/extras/selflink Example of calling the selfLink snippet to get a link to the next resource in the tree. ```APIDOC ## selfLink Snippet ### Description Creates a link or anchor to a page based on the specified direction (up, next, previous). ### Parameters - **direction** (string) - Required - Direction of the link: 'up', 'next', or 'previous'. - **id** (integer) - Optional - ID of the resource where the link must be from. Defaults to current page ID. - **tpl** (string) - Optional - Chunk name for link presentation. Defaults to `Title`. - **linktext** (string) - Optional - Alternative link text. Defaults to the resource pagetitle. ### Example ``` [[selfLink? &direction=`next`]] ``` ``` -------------------------------- ### Creating a Simple Ext JS Panel Source: https://docs.modx.com/current/en/extending-modx/custom-manager-pages/modext/modext-tutorials/5.-ext-js-tutorial-panels A complete HTML example demonstrating how to initialize and render an Ext.Panel to the document body. ```html Ext JS Panels

    Panels

    ``` -------------------------------- ### Get Select Columns for modChunk Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdoobject/metadata-accessors/getselectcolumns A basic example showing how to retrieve the column string for the 'modChunk' class. ```php $columnString = xPDOObject::getSelectColumns($xpdo,'modChunk'); ``` -------------------------------- ### Initialize extension_packages System Setting Source: https://docs.modx.com/current/en/extending-modx/custom-users Use this JSON snippet if the extension_packages system setting does not yet exist. ```json [{"extendeduser":{"path":"[[++core_path]]components/extendeduser/model/"}}] ``` -------------------------------- ### Get the modSmarty service Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.getservice A basic example of loading the modSmarty service using its key and class name. ```php $modx->getService('smarty','smarty.modSmarty'); ``` -------------------------------- ### Display Hello World with Inline PHP Source: https://docs.modx.com/current/en/building-sites/client-proofing/dashboards/widget-types/inline-php A basic example of returning a string from an Inline PHP widget to display content. ```php getAuthenticatedUser('sports'); ``` -------------------------------- ### Define Build Paths and Environment Source: https://docs.modx.com/current/en/extending-modx/tutorials/developing-an-extra/part-3 Sets up the directory structure array and includes necessary MODX configuration and class files. ```php /* define build paths */ $root = dirname(dirname(__FILE__)).'/'; $sources = array( 'root' => $root, 'build' => $root . '_build/', 'data' => $root . '_build/data/', 'resolvers' => $root . '_build/resolvers/', 'chunks' => $root.'core/components/'.PKG_NAME_LOWER.'/chunks/', 'lexicon' => $root . 'core/components/'.PKG_NAME_LOWER.'/lexicon/', 'docs' => $root.'core/components/'.PKG_NAME_LOWER.'/docs/', 'elements' => $root.'core/components/'.PKG_NAME_LOWER.'/elements/', 'source_assets' => $root.'assets/components/'.PKG_NAME_LOWER, 'source_core' => $root.'core/components/'.PKG_NAME_LOWER, ); unset($root); /* override with your own defines here (see build.config.sample.php) */ require_once $sources['build'] . 'build.config.php'; require_once MODX_CORE_PATH . 'model/modx/modx.class.php'; ``` -------------------------------- ### Initialize a Context Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.initialize Example showing how to initialize the 'sports' context. ```php $modx->initialize('sports'); ``` -------------------------------- ### Get Related Objects Example Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdoobject/related-object-accessors/getmany Retrieves all Chunk objects associated with a specific Category and iterates through them to output their names. ```php $category = $xpdo->getObject('Category',1); $chunks = $category->getMany('Chunk'); foreach ($chunks as $chunk) { echo $chunk->get('name').'
    '; } ``` -------------------------------- ### Complete Animation Example Page Source: https://docs.modx.com/current/en/extending-modx/custom-manager-pages/modext/modext-tutorials/3.-ext-js-tutorial-animation A full HTML page example combining the library includes, animation script, CSS, and the target div. ```html My Ext JS Test Page : Animations

    Animations

    ``` -------------------------------- ### Create a directory with writeTree Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdocachemanager/xpdocachemanager.writetree An example showing how to create a new directory on the filesystem using the writeTree method. ```php $xpdo->cacheManager->writeTree('/path/to/new/directory/'); ``` -------------------------------- ### Get a Resource Tree Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.gettree Example of retrieving a tree for the resource with ID 12, limited to a depth of 5 levels. ```php $treeArray = $modx->getTree(12,5); ``` -------------------------------- ### TaggerGetTags Example Usage Source: https://docs.modx.com/current/en/extras/tagger Example MODX snippet calls for common use cases: listing all tags including unused, filtering by groups, and getting tags for the current resource (using [[*id]] or [[+id]] in getResources templates). ```MODX // Get tags for all resources, including unused tags [[TaggerGetTags? &showUnused=`1`]] // Get tags from groups 1 and 3 for all resources [[TaggerGetTags? &groups=`1,3` &rowTpl=`tag_links_tpl`]] // Get tags for current resource [[!TaggerGetTags? &resources=`[[*id]]` &rowTpl=`tag_links_tpl`]] // Get tags for current resource in getResources tpl [[!TaggerGetTags? &resources=`[[+id]]` &rowTpl=`tag_links_tpl`]] ``` -------------------------------- ### GetResources TV Visible Rule Example Source: https://docs.modx.com/current/en/building-sites/client-proofing/form-customization/rules/tv-visible An example of using the getResources snippet to handle TV visibility for a specific section. ```text [[getResources@section? &parents=`315` &context=`revolution`]] ``` -------------------------------- ### Initializing build.schema.php Source: https://docs.modx.com/current/en/extending-modx/tutorials/using-custom-database-tables The initial setup for the schema build script, including path definitions and MODX initialization. ```php initialize('mgr'); $modx->loadClass('transport.modPackageBuilder','',false, true); $modx->setLogLevel(modX::LOG_LEVEL_INFO); $modx->setLogTarget(XPDO_CLI_MODE ? 'ECHO' : 'HTML'); $root = dirname(dirname(__FILE__)).'/'; $sources = array( 'root' => $root, 'core' => $root.'core/components/storefinder/', 'model' => $root.'core/components/storefinder/model/', 'assets' => $root.'assets/components/storefinder/', 'schema' => $root.'_build/schema/', ); ``` -------------------------------- ### Basic tolinks usage example Source: https://docs.modx.com/current/en/extras/taglister/taglister.tolinks Converts the 'tags' Template Variable into links pointing to Resource 123 with a 'tag' GET parameter. ```text [[!tolinks? &items=`[[*tags]]` &key=`tag` &target=`123`]] ``` -------------------------------- ### Perform Ajax request with jQuery Source: https://docs.modx.com/current/en/extras/pdoTools/Snippets/pdoPage Example of sending a GET request to a page with the page parameter to retrieve JSON data from pdoPage. ```javascript $.get('document.html?page=5', function(response) { console.log(response); }, 'json'); ``` -------------------------------- ### Copy Build Configuration Files Source: https://docs.modx.com/current/en/contribute/code/contributors-guide Create the necessary build configuration files by copying the provided samples. ```bash cp build.config.sample.php build.config.php cp build.properties.sample.php build.properties.php ``` -------------------------------- ### Print current full version Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.getversiondata Example showing how to retrieve the version data array and output the full version string. ```php $vers = $modx->getVersionData(); echo $vers['full_version']; ``` -------------------------------- ### Configuring xPDO::OPT_CONN_INIT Source: https://docs.modx.com/current/en/extending-modx/xpdo/create-xpdo-instance/connections Example of setting the initial connection criteria to ensure a read-only connection is used by default. ```php xPDO::OPT_CONN_INIT => array(xPDO::_OPT_CONN_MUTABLE => false) ``` -------------------------------- ### Example: Get iterator for Box objects with width 40 Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdo/xpdo.getiterator Demonstrates using getIterator to loop over a collection of Box objects and output their id and width. ```php $boxes = $xpdo->getIterator('Box',array( 'width' => 40, )); foreach ($boxes as $idx => $box) { echo "Box #{$idx} has an id of {$box->get('id')} and a width of {$box->get('width')}\n"; } ``` -------------------------------- ### Get Parent IDs with Context Specification Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.getparentids Example of specifying the context in the options array to ensure the correct cache is searched, which is particularly important in plugins or external applications. ```php $pids = $modx->getParentIds($id, 10, array('context' => 'web')); ``` -------------------------------- ### Define MODX_CORE_PATH in config.core.php Source: https://docs.modx.com/current/en/building-sites/contexts/virtual-host Update the MODX_CORE_PATH constant to point to the correct core directory. Use the first example for standard setups or the second if the core is located one level higher. ```php define('MODX_CORE_PATH', dirname(__FILE__) . '/core/'); ``` ```php define('MODX_CORE_PATH', dirname(dirname(__FILE__)) . '/core/'); ``` -------------------------------- ### Create a simple form with fieldSetDefaults Source: https://docs.modx.com/current/en/extras/formitfastpack/formitfastpack.field Example of a complete form using FormIt, fieldSetDefaults for global configuration, and multiple field types. ```MODX [[!FormIt? &prefix=`myprefix.` &submitVar=`submitForm`]]
    [[!fieldSetDefaults? &prefix=`myprefix.` &outer_tpl=`myWrapTpl` &resetDefaults=`1`]] [[!field? &name=`full_name` &type=`text` &class=`required`]] [[!field? &name=`favorite_color` &type=`checkbox` &options=`Blue||Red||Yellow`]] [[!field? &name=`location` &type=`select` &label=`Where are you from?` &options=`United States==US||New Zealand==NZ||Never Never Land==NNL`]] [[!field? &name=`message` &type=`textarea`]] [[!field? &name=`submitForm` &type=`submit` &label=` ` &message=`Submit Form`]]
    ``` -------------------------------- ### Removing a DOM element with Ext.get Source: https://docs.modx.com/current/en/extending-modx/custom-manager-pages/modext/modext-tutorials/4.-ext-js-tutorial-manipulating-nodes This example shows a full HTML page setup using Ext JS to remove a specific div element identified by its ID. Note that the Ext JS selector does not require a hashtag prefix. ```html My Ext JS Test Page

    Handling Elements

    I am here to stay
    I will get deleted
    One
    Two
    Three
    ``` -------------------------------- ### Outer Template Example (Revo) Source: https://docs.modx.com/current/en/extras/wayfinder Example of an &outerTpl chunk for Revolution. ```html ``` -------------------------------- ### Create a database using createSourceContainer Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdomanager/xpdomanager.createsourcecontainer Example demonstrating how to create a new database named 'MyDatabase' by defining the DSN and calling the manager's createSourceContainer method. ```php $newDatabaseName = 'MyDatabase'; $dsn = 'mysql:host=localhost;dbname='.$newDatabaseName.';charset=utf8'; $manager = $xpdo->getManager(); $manager->createSourceContainer($dsn,'myusername','mypassword'); ``` -------------------------------- ### Navigate to Build Directory Source: https://docs.modx.com/current/en/contribute/code/contributors-guide Change to the _build directory and verify the current path. ```bash cd _build pwd /your-absolute-path-here/revolution/_build ``` -------------------------------- ### Wildcard filter: starts with Source: https://docs.modx.com/current/en/extras/renderresources Matches any resource where the TV value starts with 'a'. ```text mytv==a% ``` -------------------------------- ### Run Advanced Upgrade Source: https://docs.modx.com/current/en/getting-started/installation/cli Execute this command from the setup directory to perform an advanced upgrade using the configuration defined in your XML file. ```bash php ./index.php --installmode=upgrade-advanced ``` -------------------------------- ### .htaccess Rewrite Rule Example Source: https://docs.modx.com/current/en/extras/smartoptimizer Example of a standard rewrite rule before modification. ```apache RewriteRule ^(.*)$ index.php?q=$1 [L,QSA] ``` -------------------------------- ### Example extension_packages system setting value Source: https://docs.modx.com/current/en/extending-modx/custom-resources The expected JSON format for the extension_packages system setting after successful registration. ```json [{"copyrightedresource":{"path":"[[++core_path]]components/copyrightedresource/model/"}}] ``` -------------------------------- ### Querying with Joins, Filters, and Sorting Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdoquery An example demonstrating how to join tables, apply multiple filters with specific operators, sort results, and limit the collection size. ```php $query = $xpdo->newQuery('Box'); // Remember: syntax here is classname, your alias. Note that filters use the alias. $query->innerJoin('Owner','User'); // the Owner is actually a User object, defined as Owner in the relationship alias $query->where(array( 'Owner.name:LIKE' => '%a%', 'Box.width:>=' => 10, 'Box.height:!=' => 2, 'Box.color:IN' => array('red','green','blue'), )); $query->sortby('Box.name','ASC'); $query->sortby('Box.height','DESC'); $query->limit(4); $boxes = $xpdo->getCollection('Box',$query); ``` -------------------------------- ### Row Template Example 2 (Evo) Source: https://docs.modx.com/current/en/extras/wayfinder A simple &rowTpl chunk example for Evolution. ```html
  • [+wf.linktext+] - [+wf.description+] [+wf.wrapper+]
  • ``` -------------------------------- ### Example error message Source: https://docs.modx.com/current/en/extras/simplesearch/simplesearch.simplesearchform An example of the error message displayed when no search results are found. ```text There were no search results for the search "". Please try using more general terms to get more results. ``` -------------------------------- ### FredBeforeRender modifyPermissions example Source: https://docs.modx.com/current/en/extras/fred/developer/modx_events Example of defining the modifyPermissions string to adjust user permissions. ```php $modifyPermissions = ' permissions.save_document = false; // Disable save for the user permissions.my_plugin_show = true; // Custom permission '; ``` -------------------------------- ### Write a file to the filesystem Source: https://docs.modx.com/current/en/extending-modx/xpdo/class-reference/xpdocachemanager/xpdocachemanager.writefile A basic example demonstrating how to define a string and write it to a specific file path using the xPDO cache manager. ```php $str = 'The contents of the file.'; $xpdo->cacheManager->writeFile('/path/to/the/file.txt',$str); ``` -------------------------------- ### FredBeforeRender beforeRender example Source: https://docs.modx.com/current/en/extras/fred/developer/modx_events Example of defining the beforeRender string to register Fred plugins. ```php $beforeRender = ' this.registerRTE("TinyMCE", FredRTETinyMCE); '; ``` -------------------------------- ### getArchives with Placeholder Example Source: https://docs.modx.com/current/en/extras/archivist/archivist.getarchives Example of using getArchives to set results to a placeholder and display them. ```APIDOC ## getArchives with Placeholder ### Description Displays archives for parents 4, 12, and 33, and sets the results to a placeholder called 'results'. ### Example ``` [[!getArchives? &parents=`4,12,33` &toPlaceholder=`results`]]

    Search Results

    [[!+results]] ``` ``` -------------------------------- ### Using getService inside a custom Extra Source: https://docs.modx.com/current/en/extending-modx/modx-class/reference/modx.getservice Demonstrates two ways to load a custom package service: by pointing directly to the sub-directory or by using dot-notation for the class name. ```php // Use path to point directly to the relevant sub-dir: if(!$Product = $this->modx->getService('mypkg.product','Product',MODX_CORE_PATH.'components/mypkg/model/mypkg/')) { return 'NOT FOUND'; } // Or use dot-notation in the classname and point the $path to the model directory: if(!$Product = $this->modx->getService('mypkg.product','mypkg.Product',MODX_CORE_PATH.'components/mypkg/model/')) { return 'NOT FOUND'; } ``` -------------------------------- ### FredBeforeRender lexicons example Source: https://docs.modx.com/current/en/extras/fred/developer/modx_events Example of defining the lexicons array for additional lexicons that Fred should load. ```php $lexicons = ['fredrtetinymce:default']; ```