Download - Modx Tog Sample
-
8/10/2019 Modx Tog Sample
1/90
Bob Ray
MODX: The Official GuidBuilding dynamic websites with the
MODX content management platform.
-
8/10/2019 Modx Tog Sample
2/90
Bob Ray
MODX: The Offi cial Guide
No components should EVER alter core tables or files.
Thats all Im gonna say on that one.
Jason Coward (OpenGeek) March 28, 2010
The mantra we must remember in Open Source is that
you get what you give.
Shaun McCormick (splittingred) July 21, 2010
Unequivocably, there's no way anyone can now claim
the documentation for MODX isnt up to snuff.
Ryan Thrash (rthrash) August 3, 2011
Copyright 2011 Bob Ray. All rights reserved
Publisher: MODX PressEditor: Haven Stephensechnical Editor: Shaun McCormickCover Design: kta
Interior Design: Ryan TrashProduction Coordinator: Michael HickeyIndexer: Bob Ray
ISBN: 978-0-9836194-0-6
MODX, LLC25 Highland Park Village, Ste 100-413Dallas, X 75205-2789http://modx.com/press/
42 11 04 10 9 8 7 6 5 3 2 1
-
8/10/2019 Modx Tog Sample
3/90
1|How MODX WorksTe MODX Database . . . . . . . . . . . . . . . . . . . . 2MODX vs. Tird-Party Components . . . . . . . . . . . 2Te Back End vs. the Front End . . . . . . . . . . . . . . 5Basic Building Blocks . . . . . . . . . . . . . . . . . . . . 6How MODX Delivers a Web Page . . . . . . . . . . . . 21ransport Packages . . . . . . . . . . . . . . . . . . . . 22
Other MODX Concepts . . . . . . . . . . . . . . . . . 23Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 29MODX Evolution Notes . . . . . . . . . . . . . . . . . 30
2| Installing MODXInstalling the Current Stable Release . . . . . . . . . . 36Installing Add-on Components . . . . . . . . . . . . . 52Friendly URLs, Friendly Aliases . . . . . . . . . . . . 55Installing MODX on Your Local Machine . . . . . . . 62Porting an Existing Site to MODX . . . . . . . . . . . 89Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 94MODX Evolution Notes . . . . . . . . . . . . . . . . . 95
3| The MODX ManagerTe Resource, Element, and File rees . . . . . . . . 99Te op Menu . . . . . . . . . . . . . . . . . . . . . . . 109Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 129MODX Evolution Notes . . . . . . . . . . . . . . . . . 130
4| ResourcesDocuments . . . . . . . . . . . . . . . . . . . . . . . . . 136
Weblinks . . . . . . . . . . . . . . . . . . . . . . . . . . 176Symlinks . . . . . . . . . . . . . . . . . . . . . . . . . . 177Static Resources . . . . . . . . . . . . . . . . . . . . . . 178emplate Variables and Access Permissions . . . . . . 179Other Resource Operations . . . . . . . . . . . . . . . 179Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 183
MODX Evolution Notes . . . . . . . . . . . . . . . . . 1845| Templates and Template Variablesemplates . . . . . . . . . . . . . . . . . . . . . . . . . . 190Creating a emplate . . . . . . . . . . . . . . . . . . . . 190
An Example emplate . . . . . . . . . . . . . . . . . . 191Example emplate: A Closer Look . . . . . . . . . . . 192Deciding What to Put in a emplate . . . . . . . . . . 198Using ags in a emplate . . . . . . . . . . . . . . . . . 199emplate Variables . . . . . . . . . . . . . . . . . . . . 199Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 226MODX Evolution Notes . . . . . . . . . . . . . . . . . 227
6| Chunks and Properties
Introducing Chunks . . . . . . . . . . . . . . . . . . . . 230Creating a Simple Chunk . . . . . . . . . . . . . . . . . 230Using Chunks with Other ags . . . . . . . . . . . . . 232Other Uses or Chunks . . . . . . . . . . . . . . . . . . 236Introducing Properties . . . . . . . . . . . . . . . . . . 247Sending Properties in the Chunk ag . . . . . . . . . 249Deault Properties Versus Property Sets . . . . . . . . 249
Working with Deault Properties . . . . . . . . . . . . 252How Deault Properties are Used . . . . . . . . . . . . 255Property Sets . . . . . . . . . . . . . . . . . . . . . . . . 256Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 263MODX Evolution Notes . . . . . . . . . . . . . . . . . 264
7 | Snippets and PluginsWorking with Snippets . . . . . . . . . . . . . . . . . . 268Working with Plugins . . . . . . . . . . . . . . . . . . . 289Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 305MODX Evolution Notes . . . . . . . . . . . . . . . . . 306
8 | Advanced Snippet Operations
MODX get*() Methods . . . . . . . . . . . . . . . . . . 310Object Methods . . . . . . . . . . . . . . . . . . . . . . 326Working with Resources, Elements, and Users . . . . 352Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 415MODX Evolution Notes . . . . . . . . . . . . . . . . . 416
9 | Site Organization and ContextsSite Organization . . . . . . . . . . . . . . . . . . . . . 419Contexts. . . . . . . . . . . . . . . . . . . . . . . . . . . 424Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 434MODX Evolution Notes . . . . . . . . . . . . . . . . . 435
10 | MODX SecuritySecurity System Overview . . . . . . . . . . . . . . . . 438
Security Elements . . . . . . . . . . . . . . . . . . . . . 442Working with MODX Security . . . . . . . . . . . . . 454Controlling Access in the Front End . . . . . . . . . . 468Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 496MODX Evolution Notes . . . . . . . . . . . . . . . . . 497
11 | Customizing the MODX ManagerAltering the op Menu . . . . . . . . . . . . . . . . . . 502Form Customization . . . . . . . . . . . . . . . . . . . 513Custom Manager Pages . . . . . . . . . . . . . . . . . . 523Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 533MODX Evolution Notes . . . . . . . . . . . . . . . . . 533
12 | Using Common ComponentsInstalling Components and Property Sets . . . . . . . 536Creating an FAQ Page with EZaq . . . . . . . . . . . 539Creating a Contact Page with SPForm . . . . . . . . . 543Using Breadcrumbs to Show the Current Path . . . . 551Using Waynder to Create a Menu . . . . . . . . . . . 555Using getResources to Aggregate Content . . . . . . . 565Using FormIt to Create and Process Forms . . . . . . 571Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 594MODX Evolution Notes . . . . . . . . . . . . . . . . . 594
13 | Creating Transport Packagesransport Package Overview . . . . . . . . . . . . . . 600
A Simple ransport Package . . . . . . . . . . . . . . . 605
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . 625MODX Evolution Notes . . . . . . . . . . . . . . . . . 626
AppendixMODX API . . . . . . . . . . . . . . . . . . . . . . . . . 629PHP Primer . . . . . . . . . . . . . . . . . . . . . . . . 652MODX Objects Reerence . . . . . . . . . . . . . . . . 690Using SMP to Send Mail in MODX . . . . . . . . . . 696MODX System Events . . . . . . . . . . . . . . . . . . 697
Table of Contents
-
8/10/2019 Modx Tog Sample
4/90
AcknowledgmentsCountless people have been invaluable in the production o this book. First and oremost, I
owe a debt o gratitude to the ounders and core developers o MODX: Ryan Trash (rthrash),
Jason Coward (OpenGeek), and Shaun McCormick (splittingred). Tey have developed a rst-
class Open Source CMS, and this book would not have been possible without their support
and patience. Shaun served as the books technical editor and deserves special credit or
ensuring its accuracy. Haven Stephens, the books editor, played a critical role in eliminatingcountless errors and making sure that the explanations in the book were as clear as possible.
I would also like to thank the many users o the MODX Forums, both those whose answers
have taught me almost everything I know about MODX and those whose questions led to
the creation o this book. In particular, Id like to thank the ollowing people (MODX Forum
usernames in parentheses):
Susan Ottwell (sottwell), Jelle Jager (obyL), (ganeshXL), David Molliere (davidm), (kon-
gondo), (doze), (ZAP), Zaigham Rana (Zi), Andreas Wettainen (mrhaw), Jay Gilmore
(smashingred), Shane Sponagle (dev_cw), (coroico), Kyle Jaebker (kylej), Garry Nutting
(garryn), Jeff Whiteld (Bravado), (Everett), (inx), Mike Reid (pixelchutes), Jared Carlow
(jaredc), (Dr. Scotty Delicious), (Carsten), Steve Hamblett (shamblett), (NetProphE),Adam Crownoble (aNoble), (netnoise), (sirlancelot), Aaron Wardle (Onesmarthost), (Pho-
towebmax), Erik Bjorn (Sylvaticus), (snop), (mademyday), Keith Penton (kp52), (char-
liez), (bob1000), (Chuck), (therebechips), Dimitri Hilverda (Dimmy), (Soshite), Adrian
Lawley (aff ), (sinbad), Bruno Perner (Bruno17), (Breezer), (mmjaeger), (AMDbuilder),
(sharkbait), (chinesedream) (cipa), (Chuckrukk), (Paprikas), David Bunker (bunk58),
(samba), (paulp), (Byzantium), (SandersDesign), (virtualgadjo), James Ehly (devtrench),
Mark Hamstra (Mark H.), (treigh), (hotdiggity), (ottogal), (anso), (pleth), (lossendae),
(mconsidine), ( Jul), (xdom), Luca Reghellin, (microcipcip), (Pandy06269), Helen Warner
(Muggins), Ivan Salcedo (odeclass), Stean Moser (stean), Rob Backus (robb), John Hughes,
Zuriel Andrusyshyn (zurie).
My apologies to the many others whose names Ive omitted either rom lack o space or
memory lapse.
Id also like to thank my cat, Cosmo, who spent many hours each day or over two years
curled up next to me as I worked on the book at my computer. His comments on the book
were invaluable.
Disclaimer of Warranty (Legal Mumbo Jumbo)
All o the inormation, instructions, and recommendations in this book are provided on a strictly as is basis
without any warranty, expressed or implied. In particular, any and all warranties o tness or use or merchant-
ability are disclaimed. Neither MODX nor Bob Ray personally shall be held responsible or any direct, indirect,
incidental, or consequential damages that may result rom the use o material in this book or anything any reader
does as a result o reading any part o the book or any associated web site. It is up to the reader to determine the
suitability o any directions or inormation presented in the book. Furthermore, it is the responsibility o the
reader to determine i any inormation, instructions, or recommendations given in the book are appropriate
based upon his or her particular situation. Te author and publisher cannot be held accountable or decisions
made based upon material in the book.
-
8/10/2019 Modx Tog Sample
5/90
-
8/10/2019 Modx Tog Sample
6/90
MODX: The Offi cial Guide i
Introduction
MODX is an advanced Open Source Content Management System (CMS). I you are not
amiliar with the term CMS, think o a word processor or web sites, but on steroids. A
CMS will usually provide you with a graphical view o your web site, a database that stores
the sites content, and one or more editors or creating web pages and populating them
with links, lists, headings, and ormatted text.
Every CMS tries to provide a convenient and powerul user interace or creating andmaintaining web sites, but to some extent, convenience and power are in opposition to
one another. Some CMS platorms, like WordPress, put convenience above power. I you
want a standard blog with a ready-made look and eel, WordPress provides a surprisingly
riendly and intuitive user interace or creating and maintaining one.
MODX, on the other hand, leans more toward the power side o the equation. Te learning
curve is a little steeper, but MODX allows you much more reedom in the design o your
web site, more powerul tools you can use to make the web site unique, and the ability to
customize the CMS itsel.
MODX is also a powerul Content Management Framework (CMF). Tis means that thebuilding blocks o MODX can actually be used to create any number o different CMS
platorms. We will cover customizing the MODX user interace in later chapters. For the
most part, however, the use o MODX as a CMF is beyond the scope o this book, which
is mainly about MODX the CMS.
One guiding principle o MODX is to put as ew restrictions on the web developer as pos-
sible. MODX puts no limits on the CSS and HML code you use to build your site, and
you can easily add PHP or JavaScript code to meet any need. One illustration o this ex-
ibility is that you can take virtually any existing web site and make a MODX web site out
o it that looks exactly the same to a ront-end visitor. rying that with many other CMS
platorms will leave you cursing and tearing your hair out.
By the time youve nished reading this book, you should be able to use MODX to create
new web sites or to port existing web sites to MODX. It was my goal in writing this book
to provide all the inormation you need to use the basic building blocks o MODX to meet
your needs as a web designer/developer.
-
8/10/2019 Modx Tog Sample
7/90
Introduction
ii MODX: The Offi cial Guide
About This BookBeore we dive into MODX, we need to discuss a ew things about this book. In the ollowing
sections, well look at who the book is or, how it is organized, and how the typography o
the book can help you understand what youre looking at.
AudienceTis book is or anyone who wants to use MODX or web site design, development, and
maintenance. In order to get the most out o this book, you should have a basic amiliarity
with (X)HML, CSS, and how the two interact in the rendering o web pages.
You will also see some PHP code in the book. You can do a lot with MODX without knowing
PHP, but to get the most out o MODX, you really should have at least some knowledge
o PHP. I you dont, never ear. PHP is a relatively easy computer language, and the PHP
Primer in this books Appendix will help you get started.
Tere are many excellent PHP tutorials on the Web, and lots o expert MODX users knew
no PHP when they started out. Ofen, they created a web site with no PHP, and then
learned PHP, a little bit at a time, as they began to make their web site more and more
interesting and easier to maintain.
Tis book is perectly suitable or MODX beginners but contains plenty o in-depth inor-
mation or power users as well. I you are brand new to MODX, some parts o the book
may go over your head the rst time you read them. Over time, however, you will grow
more amiliar with how MODX works, and they will gradually begin to make sense to you.
At rst, I tried to put material or beginners at the beginning o the book and save the
more advanced inormation or later. Because o the way MODX works, however, it just
wasnt possible. As a result, youll see things that may conuse you on the rst pass. Youshould be able to ignore them and create a perectly good web site using the things you
do understand. Later, as things make more sense to you, youll be able to rene your site
to take advantage o MODXs more advanced eatures. Te book is also meant to serve as
a reerence manual or both beginners and experts.
-
8/10/2019 Modx Tog Sample
8/90
MODX: The Offi cial Guide iii
Organization of The BookGenerally, the book is organized on the basis o MODX objects, such as resources, chunks,
snippets, plugins, placeholders, etc. I you are new to MODX, you wont be amiliar with
these at rst. Afer reading Chapter 1, however, you should have a air idea o what they
are and how they work together. Later in the book, well look at each MODX object in
depth. Because the objects constantly interact with each other, youll be learning about
them all bit-by-bit as we go along.
ConventionsA number o typographical conventions are used throughout the book to make it easier to
understand what youre looking at. Tere are two main typeaces or content in the book:
Te regular ont (used or this sentence) and the code ont. Te code ont looks like this
when it appears in a regular ont paragraph: This is the inline code font. When it
appears in a separate paragraph, it looks like this:
This is the code snippet font.
Te code ont is used or all (X)HML, CSS, and JavaScript code and or all MODX tags
and their contents. It is also used or le and directory names and or path names and or
text to be entered in a eld in the MODX Manager.
MODX internal variables such as system event names, settings, and resource/template
variable eld names will also be in the code ont, but to make them distinguishable, they
will be in boldace type wherever they appear:
OnManagerFormSave, site_start, pagetitle.
Key terms will generally be in the regular ont in italics when they rst appear. ermsreerring to MODX objects (snippets, template variables, chunks, plugins, categories,
placeholders, etc.) will be in lowercase when they appear in text except at the beginning
o a sentence.
Names o resources or elements that you will be creating and editing yoursel, will be
in italics in the code ont when they rst appear, then in the regular ont in roman type,
usually in CamelCase:
Create a chunk called FooterChunk. Te FooterChunk will contain code or the
page ooter.
erms reerring to specic areas o the MODX Manager or to orm elds in the Managerwill generally be in initial caps and in the regular ont:
Create/Edit Resource panel, Long itle, Alias, Package Manager
-
8/10/2019 Modx Tog Sample
9/90
Introduction
iv MODX: The Offi cial Guide
Shorthand reerences to Manager commands that use menus or navigation will be in bold
and have arrows between them:
Go to Tools Package Management
Longer descriptions o Manager actions in the text will use initial caps and quotation marks
around buttons and menu choices that you are meant to select:
Select System on the op Menu, then click on Package Management.
Field names and tab names used in the MODX Manager will be in initial caps when reer-ring to the specic area o the Manager, but in lowercase when discussing them as general
objects. Tey will be enclosed in quotation marks when they are included in directions to
click or select them, but used without the quotation marks in general discussion:
Click on the Elements tab.
Chunks are listed on the Elements tab.
Chunks are classied as elements.
Te names o specic resources and elements will generally be in CamelCase in the text.
Tey will usually be in the code ont and italics when they rst appear (especially in direc-
tions to create them):
Create a resource called News.
Lets create our ShowListsnippet.
Later reerences to them will be in the regular ont in CamelCase:
Te FooterChunk contains all the elements shown in the ooter o the page.
Tey will be enclosed in quotation marks in instructions to click or select them in the
Manager:
Click on the ShowList snippet on the Elements tab.Variable names (including snippet properties) will generally start with a lowercase letter
and have the rst letter o each ollowing word capitalized. Tey will be in the code ont:
$wordLength, $fontColor, $textHeight, though there are some exceptions to this rule.
Property names, MODX settings, and placeholder names, or example, are ofen in all
lowercase with an underscore character between words: site_start, blocked_until.
MODX system event names are in CamelCase and begin with a capital letter. All start
with On: OnManagerFormSave. Resource eld names are in all lowercase, and a ew have
underscores while most dont: pagetitle, longtitle, pub_date, unpub_date.
As mentioned earlier, MODX settings and system event names will be in the code ont
in bold. For resource eld names, the caption used in the Manager will be in initial caps
-
8/10/2019 Modx Tog Sample
10/90
MODX: The Offi cial Guide v
in the regular ont (e.g., Page itle, Publish Date). Te actual eld names used internally
by MODX (and by users in tags and snippets) will be in the code ont and bold (e.g.,
pagetitle, pub_date).
When a MODX tag or example contains a name that the user will supply, the term will be
in italics:
[[SnippetName? &property1=`value1` &property2=`value2`]]
In the above example, the user is expected to replace all the words in italics. Tis is important
because new users sometimes type in the example exactly as it is written and are surprised
when it doesnt work.
Ive tried to be as aithul to these conventions as possible, but this is a long book with many
complicated reerences. I hope the reader will orgive the inevitable errors in typography.
nBecause the page width of this book is limited, some lines of PHP and HTML
code that should be on a single line are broken into two or more lines. I tried
to break them in a way that doesnt harm the users understanding of what the
code does, but it wasnt always possible. The extra lines of code created will
always be indented.
The only time the lines must be combined is for Input Option Values of tem-
plate variables. Heres an example:
Red==Red as a rose||Blue==Blue as the sky||
Green==Green as the grass
The lines above must be entered as a single line, but MODX wont let you use a
carriage return for Input Option Values anyway, so the need to combine themshould be obvious.
In all other cases that Im aware of, the code can be entered as written and
no harm will be done the PHP and HTML parsers are very forgiving about
formatting but you should feel free to combine the split lines to fit your
coding style. Generally, the only negative effect of the split lines will be on the
formatting of some raw HTML code youll see if you select View Source in
your browser.
-
8/10/2019 Modx Tog Sample
11/90
Introduction
vi MODX: The Offi cial Guide
About MODXIn the ollowing sections, well look at whether MODX is a good choice or you, learn a
little bit about the history o MODX, and discuss the various versions o MODX. Well also
take a look at the architecture and key eatures o MODX.
Is MODX for you?MODX is designed to be useul to everyone rom beginning web designers to advanced
Content Management System developers, but it is somewhat diffi cult or the ormer. I
you are looking or a system that will do everything you want out-o-the-box and let you
produce a nished web site without getting your hands dirty, MODX is probably not or
you. For a standard blog, or example, WordPress might be a better choice. You install it,
select a theme (or use the deault one), and begin entering your posts.
Where MODX shines is in cases where you want a unique web site with active pages that
you design yoursel. Its exibility and power are unequalled in the CMS world. I you can
describe what you want your web site to do, the odds are good that you can do it in MODX.
My rst MODX web site, or example, was a site I designed or a local political organiza-
tion. Te site had the usual pages: a page describing the organizations offi cers, a volunteer
page, a page or the local elected offi cials with links to their web sites, a page containing
the organizations bylaws, a page where users could download issues o the organizations
newsletter, etc. Te site also had a ront page with excerpts rom news posts, each with a
link to the ull post.
Next, I added a series o photo galleries or various events and put a random photo rom one
o the galleries under the menu on the ront page that served as a link to the photos gallery.
Ten came a undraising thermometer that showed the current level o contributions.I set up one user as the photo editor who could easily create new galleries and upload
photos in the ront end. I set up a news editor who could write new articles that would
automatically show up in the news section and be excerpted on the ront page. I set up
a newsletter editor who could upload new newsletters in .PDF ormat. Each editor had
access to only his or her own section o the site.
I learned MODX, created the site, and wrote simple instructions or each user in a surpris-
ingly short time less than a week. Te site has been rock-solid ever since with almost
no intervention on my part.
On one o my next MODX sites, the client wanted a page with seasonal photos and adiscount coupon that changed automatically our times a year, with the seasons. I was
-
8/10/2019 Modx Tog Sample
12/90
MODX: The Offi cial Guide vii
able to add this in MODX using a simple custom snippet in about an hour. Doing this on
most other CMS platorms would have taken much, much longer and would have been
extremely rustrating.
In order to use MODX at all, youll need some basic amiliarity with CSS and (X)HML.
Its best i you have created a ew web sites beore diving into MODX. You dont need to
know PHP to use MODX, but it denitely helps. Many MODX users end up learning PHP
a little bit at a time as they attempt to get the most out o the CMS.
I you dont know any PHP at all, dont be put off by the examples o PHP code in the book.Tey are there or advanced users, and you can still do quite a lot with MODX without
knowing PHP. Te odds are that you will pick it up as you develop your MODX skills and
can then go back and read over any sections that conused you at rst. Tere is a PHP
Primer in the Appendix at the end o the book that will help get you started.
A Brief History of MODXIn 2004, Ryan Trash and Raymond Irving started working on what was later to become
MODX. Te initial MODX project was a combination o the DocVars add-on or the EtomiteCMS and Raymonds web-user add-on. Tere was resistance to the MODX project at
Etomite, and the two eventually lef that community to work on MODX as a separate CMS.
MODX 0.9.0 began as a ork o Etomite but has developed into an independent CMS plat-
orm, and as o the release o MODX 2.0 Revolution, all reerences to Etomite are gone
rom the MODX code.
In May o 2005, Jason Coward joined the project, and in 2007, Raymond Irving lef (ami-
cably). Jason became the principle architect o the MODX core code. In 2008, Shaun McCor-
mick joined the project and is now primarily responsible or the MODX Manager interace.
MODX has an extremely creative and responsive user community, and countless MODX
users have contributed to the development process over the last ew years.
In 2009, MODX Version 0.9.6 was supplanted by two new versions. Te 0.9.6 designation
was misleading by that time, MODX was a very robust and mature product. As o this
writing, MODX exists in two orms: MODX 1.x.x Evolution and MODX 2.x.x Revolution.
Versions of MODXIn 2009, both MODX 1.0.0 Evolution and MODX 2.0.0 Revolution were released. I you
visit the MODX Forums, you may see them reerred to as Evo and Revo or short.
-
8/10/2019 Modx Tog Sample
13/90
Introduction
viii MODX: The Offi cial Guide
Tere are many similarities between the two, especially rom the point o view o the user.
Under the hood, the two are quite different. Well look at some o the similarities and di-
erences in the ollowing sections. For now, well say that the main components o MODX
discussed in this book (chunks, snippets, templates, template variables, plugins, resources,
settings, and tags) exist in both versions and play the same role in each.
Te MODX Manager user interace has been redesigned or MODX Revolution but is similar
enough that most users have little or no trouble making the transition rom one to the other.
Tis book is written primarily rom the perspective o MODX Revolution since that isthe uture o MODX. Tat said, most o the content in the book will apply equally well to
either version, and there is a section at the end o each chapter describing how the content
o that chapter applies in MODX Evolution.
MODX Evolution
MODX 1.0.0 Evolution is a mature, stable release o the original MODX codebase with a set
o standard add-ons or things like menus, photo galleries, user management, and content
aggregation. It provides a airly seamless upgrade or all legacy MODX sites.
Te version numbers o earlier versions o MODX (e.g., 0.9.2, 0.9.6) are somewhat mis-
leading. Te version numbers imply that they were beta versions. In act, they were (and
still are) very mature and used in thousands o production web sites.
MODX Evolution has been around longer, and as o this writing, is more amiliar to most
MODX users than Revolution and has more available add-ons. Evolution also has a smaller
ootprint and takes somewhat less memory to install and use. Revolution, however, is
more robust and more secure. Revolution is a signicant technical advance compared to
Evolution and represents the uture o MODX.
MODX Revolution
MODX 2.0.0 Revolution (which appeared briey as version 0.9.7) is a complete re-write
o the MODX core code and Manager with a new tag syntax and many revolutionary ea-
tures (hence the name). Te Manager is somewhat easier to navigate and has a number
o extremely convenient eatures like drag-and-drop editing and the ability to create new
elements and resources and clear the cache in pop-up windows without leaving your
current work. Revolution also introduces convenient grids or editing language strings,
system settings, and snippet properties.
By ar the most revolutionary eature in Revolution rom the average users perspective
is the Package Management system. In Revolution, add-ons can be downloaded rom the
-
8/10/2019 Modx Tog Sample
14/90
MODX: The Offi cial Guide ix
MODX repository and installed with a ew clicks in the Package Manager. In Evolution,
you have to download a .ZIP le or each add-on, unzip it, and cut and paste code into
MODX elements and resources you create yoursel a much more time-consuming and
error-prone process.
Tere is also much or the developer/web programmer to love in MODX Revolution.
Tere is a completely new database API based on xPDO, which provides an effi cient and
easy-to-use way to read, create, and update all MODX objects. It also allows you to easily
pull data rom multiple MODX tables (with one query) in a single, elegant line o code.
Which Version Should I Use?
I you are upgrading an existing site that you dont work on very ofen, MODX Evolution
may be a better choice or you. Evolution is also a better choice i you need to install and
run your web site with limited memory. As I write this, Revolution needs at least 32M o
memory to install (although there are plans to remedy this), so i your web host restricts you
to 8M or 16M o memory and you are not allowed to change that, Evolution is the better
choice. Most web hosts have higher limits, and many allow you to modiy the amount o
available memory.
nMany of the concepts described in this book are relevant for either version.
If you will be working through the examples in the book, however, MODX
Revolution is really your only choice. All of the tags and much of the code pre-
sented in the books examples will only work as written in MODX Revolution.
In other situations, the key to making the choice is the available add-ons. At this writing,
some o the add-ons available or MODX Evolution have not been ported to Revolution
though most o the important ones have. By the time you read this, there will certainly be
more o them available in Revolution, but some less-popular third-party components may
still not be available. Many o the standard MODX snippets and plugins have been replaced
by aster and better versions or Revolution, and some have also been integrated into the
MODX Manager. You should assess your needs and examine the available components (ask
in the MODX Forums, i necessar y) beore making your decision.
Another consideration is the permissions system. MODX Revolution offers much more
sophisticated and nd-grained control over what users can do and see in the MODX
Manager. Te price o that control, however, is a steeper learning curve. Once the per-
missions or Revolution are set correctly, you can usually orget about them, but the initial
process can be somewhat rustrating and time-consuming. I you will be the only user othe site, Revolutions deault settings will be ne or you. I you have several users with
-
8/10/2019 Modx Tog Sample
15/90
Introduction
x MODX: The Offi cial Guide
different access rights and the permission system is relatively simple, Evolution may be
a better choice. I you need to have users who will belong to more than one user groups
and want them to have different capabilities or each groups documents, then Revolution
is the better choice.
Assuming that the add-ons you need are available in Revolution (or you are capable o
developing or adapting them yoursel) and the Revolution permission system meets your
needs, I would recommend it or everyone, including beginning MODX users. Revolution
is a robust CMS platorm and has many eatures that make it a superior choice.
Architecture and Key FeaturesTe overriding principle in the design o MODX is reedom or the user. o the best o the
designers abilities, MODX puts no restrictions on what you can put in your web site. MODX
users are ree to use any (X)HML, CSS, PHP, or JavaScript code to meet their needs.
You could port most existing web sites to MODX simply by pasting the code rom each
page into a MODX template, moving any PHP code into snippets, and creating an empty
document or each page that uses that pages template. Doing this would be a horriblemisuse o MODXs power, but the act that its possible shows how ew restrictions MODX
places on the user.
I you are not a power user/developer, you probably wont care whats under the hood in
MODX. For those who do care, here is some inormation about the structure and design
o MODX. Dont be put off i some o the ollowing material goes over your head. You can
create very impressive MODX web sites without knowing any o it.
xPDO
MODXs data handling is based on xPDO. Created by MODX core developer Jason Coward,
xPDO is a PHP-based object-relational bridge that is designed to provide object-ori-
ented access to a variety o underlying database platorms such as MySQL, SQLite, and
PostgreSQL.
Both lightweight and robust, xPDO now requires PHP 5.1.1 or higher. It is signicantly
aster now that it no longer has to support PHP 4. It allows simple le-based result-set
caching and custom cache implementations that can be optimized or particular needs. It
also supports JSON caching or optimizing Ajax applications.
Using xPDO allows advanced MODX web site developers to easily integrate custom data-
bases into a MODX install using built-in MODX methods. It also provides a relatively simpleAPI that developers can use to obtain inormation rom the MODX database.
At this writing, xPDO supports MySQL and Microsof SQL databases, with more to ollow.
-
8/10/2019 Modx Tog Sample
16/90
MODX: The Offi cial Guide xi
User Interface
Te MODX Manager is an Ajax-based user interace implemented with Smarty and ExtJS.
In the Manager, users can create and edit content as well as perorm a wide variety o
administrative tasks like user management, publication scheduling, generating reports,
installing add-on components, and adding user-created custom snippets and plugins. Te
MODX Manager is designed to be productive and intuitive.
In MODX Revolution, (unlike Evolution) many Manager tasks can be perormed in pop-up
windows, so users can create and update resources and elements and clear the MODX
cache without leaving their current location in the Manager. Drag-and-drop unctionality
also increases productivity and reduces potential errors in the Manager.
Because the Manager is a web-based application, users can manage their MODX site rom
anywhere they have web access using no tools other than a web browser. MODX supports
a wide variety o web browsers.
Te Manager can be easily customized, and it can look very different or different users.
Users can be restricted to certain areas o the Manager, and the areas they see can be
customized or their particular needs and abilities. Multiple editors can be easily plugged
into the Manager or use in creating and editing content as well as or managing variouskinds o code.
Design Philosophy
MODX is designed around several basic principles. Tese include security, robustness,
speed and effi ciency, object-oriented design, core independence, and ne-grained cache
control and user management.
SecurityMODX is designed to be as secure as possible. All user input is analyzed or potential
hazards, and no PHP code is allowed or executed in most MODX resources and elements.
PHP code can only appear in snippets and plugins, and its execution is careully regulated.
All PHP code in the system can be contained in the database or in the MODX core, which
can be shielded rom web access. Te user security system is also extremely tight and pre-
vents unauthorized users rom accessing sensitive areas o the Manager.
-
8/10/2019 Modx Tog Sample
17/90
Introduction
xii MODX: The Offi cial Guide
Robustness
MODX is designed rom the core outward to be solid and ault-tolerant. Changes are
evaluated and tested to ensure that they cause no problems in the operation o the system.
MODX sites are generally rock-solid with virtually no downtime due to errors in MODX.
Speed and Effi ciency
Te developers o MODX are constantly proling and reactoring MODX objects and their
methods to make MODX as ast and effi cient as possible. Te caching process ensures that
requently accessed content and code are cached or maximum perormance.
MODX is also designed to be a lightweight platorm. Users install only the components
they need or a particular site, and components are designed to be exible and powerul
enough that users can meet their needs with a small number o add-on components.
Object-oriented Design
MODX Revolution is object-oriented rom the ground up. Every MODX object is a truePHP object, and all use o objects is through their properties and methods. Chunks, snip-
pets, templates, and template variables, or example, are all subclasses o the modElement
class. Te MODX parser makes ull use o the object methods available through the basic
class. Tis makes the MODX core both effi cient and easily extendable.
MODX also makes it easy to adhere to the principles o the model-view-controller (MVC)
design philosophy by acilitating the separation o content, logic, and presentation.
Core Independence
Another principle is the complete separation o the MODX core rom the content o the
site. Te core can be located in a directory that is not accessible rom the Web or security.
One MODX core can also support more than one web site.
Central to the separation o the core is a wide variety o built-in ways to extend and tap
into the core processes. Tere is a well-developed API or accessing core methods and a
comprehensive list o system events that re at various points in the operation o the core.
Users can create PHP snippets that use the API to get inormation rom the core and the
database. Tey can also create PHP plugins that listen or the appropriate system event
and step in to alter the processing at that point. Te main purpose o these capabilities is to
give the user the ability to do anything he or she can think o in MODX without touchingthe core code. When users upgrade to a new version o MODX, none o their custom work
-
8/10/2019 Modx Tog Sample
18/90
MODX: The Offi cial Guide xiii
has to be done over again. Advanced developers can even create a custom parser class to
override or extend the behavior o the MODX parser. Custom elements and resources are
also a possibility or users with particular needs.
Fine-grained Cache Control
Another key principle is granular control o the MODX cache. Parts o the core are cached
as needed, and various parts o each ront-end page can easily be designated as cached oruncached by the user. In MODX Revolution, any element or resource can be designated as
cached or uncached. As a result, nothing is cached but content and code that needs to be
rapidly accessible. Because o MODXs xPDO base, database result-sets are also cached on
an as-needed basis. In addition, there are a number o system settings that control whether
certain MODX objects are cached and or how long.
Fine-Grained User Management
Like the caching process, user management is extremely granular in MODX Revolution.
Since resources such as documents are in a hierarchical structure on the Resources tab,users can be limited to particular branches o the Resource tree shown on the Resources
tab. In addition, individual resources can be placed in resource groups and individual ele-
ments can be placed in categories. Specic resource groups and categories can be made
accessible only to members o specic user groups. Users can have designated roles that
restrict them to specic actions in the Manager such as viewing, saving, editing, publishing,
and unpublishing documents. Finally, the MODX Manager can be customized so that each
user sees a completely different version o the Manager.
-
8/10/2019 Modx Tog Sample
19/90
-
8/10/2019 Modx Tog Sample
20/90
Chapter 1
How MODX Works
Using a Content Management System (CMS) is quite a bit different from just creatingweb pages and linking them together to make a site. A CMS takes a while to learn (and
one as exible and powerful as MODX takes a little longer). Te time you spend getting
familiar with MODX, however, will pay off many times over. It will make maintaining web
sites easier and faster. It will also allow you to easily create web-site features that would
be extremely diffi cult and time-consuming to produce without a CMS backing you up.
While many CMS platforms make life easy by severely restricting what you can do (with
structured templates, built-in and add-on components that are hard to modify, hard-coded
entity and directory names, etc.), MODX does just the opposite. Letting users do what-
ever they want is a primary goal of the MODX development team. Te exibility and
freedom of MODX come with a price, however. Because there are fewer rules, its harder to
know how to solve any given problem. Its also a little easier to shoot yourself in the foot.
In this chapter, well touch on the various parts of MODX and how they work together to
let you manage web sites. In later chapters, well cover the mechanics of using the MODX
Manager, and the details of the various parts of MODX such as web resources, content ele-
ments, and les. Tis chapter is just to get your feet wet, introduce these elements, and give
you an overall sense of how MODX does its job.
MODX: The Offi cial Guide 1
-
8/10/2019 Modx Tog Sample
21/90
The MODX DatabaseI you are coming to MODX rom another Content Management System(CMS) such as
Drupal or Joomla!, you probably already have some sense o how such systems work. I,
instead, youre used to working in straight (X)HML and CSS, you may not be aware o
how a CMS like MODX stores and presents the sites content. New users o MODX some-
times install the MODX sample site then look (unsuccessully) or the HML page les.
Te reason they dont nd the HML les is that MODX, like most other CMS platorms,
stores the page content in a MySQL or Microsof SQL database (although uture versions
o MODX will be able to use a variety o other database platorms and will allow you to
store web resources and content elements in les rather than the database i you wish).
When a user visits one o your pages, MODX goes to the MODX database, gets the inor-
mation it needs or the requested page, assembles it, and sends it off to the users browser
or display. Tis all happens behind the scenes. Many MODX users create sites without
ever dealing with the database or the process o saving and retrieving the inormation. o
really make MODX sing, however, youll eventually want to learn about how some o the
behind-the-scenes processes work. For now, well just say that you create web resources(most o which will be documents) in the MODX Manager(also called the back end)
and save them. When a user visits a particular web page at your site, MODX retrieves the
appropriate content and sends it off to the users browser or display. A lot can happen to
that content beore the user sees it, but well get to that later. First, lets look at the di-
erences between MODX and its add-on components and between the back end and the
ront end o a MODX site.
MODX vs. Third-PartyComponentsIn MODX Revolution, there has been a very determined effort to separateMODXitsel
rom componentscontributed by others that extend or add to the unctionality o MODX. A
number o third-party components(also called add-ons, 3PCs, extras, add-on components,
or just components) were distributed and installed with earlier versions o MODX as a
convenience to users. Tey added unctions like custom menus, aggregated content display,
1|HowMO
DXWorks
2 MODX: The Offi cial Guide
-
8/10/2019 Modx Tog Sample
22/90
text editors, photo galleries, etc. People ofen assumed that these were part o MODX itsel,
and when problems occurred, people complained about bugs in MODX. Te MODX core
developers would have to explain, over and over, that these were not part o MODX.
With MODX Revolution and uture versions, only MODX is installed to begin with. It
includes just three directories: /core, /connectors, and /manager(asetup/directory is
present at rst but is usually removed afer a successul install). Users are also ree to move
and rename those three directories i they wish or even to install a different or customized
manager to administer their sites.Once youve completed the MODX base install, you can then easily add whatever third-party
components meet your needs. Tis helps keep your MODX site rom being loaded down
with components you dont need. Te download and install process or components is
all done in the Manager, and it allows you to browse through the available components,
download them, and install them with a ew mouse clicks.
I you nd you need more components later, new components become available, or new
versions o existing components are released, its a simple matter to browse the package
repository and install them. Another advantage o this separation o the base install rom
third-party components is that the base install can remain pure. It is unaffected by the
installation and upgrading o components, and conversely, updating the base install to a
new version o MODX is unlikely to affect any installed components.
Although the base MODX install contains no third-party components, by the time you
read this, there may be additional distribution versions o MODX available that include
various third-party components tailored to a specic purpose, such as a blog site, a photo
gallery site, etc.
MODX ItselfTe heart o MODX is in the /coredirectory (although you are ree to rename and/or
relocate that directory during the install, this is not recommended or new users). Te
/coredirectory contains the essential parts o the MODX content management engine.
You could create a working web site with the tools available in the initial install, but it
would have no dynamic menus, no WYSIWYG editor, no content aggregators none o
the things that really make MODX worthwhile or users. In order to gain those eatures,
users need to add third-party components.
MODX: The Offi cial Guide 3
-
8/10/2019 Modx Tog Sample
23/90
MODX Third-Party ComponentsTe offi cial term or anything added to the base MODX install is third-party component.
Tird-party component is kind o a mouthul, so they are ofen reerred to as 3PCs, extras,
or just componentsor short. At this writing, components is the more common term,
but extras is gaining ground. Components are usually installed with a ew mouse clicks
in the Package Management section o the MODX Manager.
Components are divided into two groups: add-ons and core extensions. Add-onsdo notmodiy or extend the MODX core but provide extra unctionality or MODX. Core extensions
(sometimes reerred to as just extensions) actually change or extend the MODX Core.
An extension might, or example, replace the MODX user class with a class that contains the
same methods and member variables but adds some new ones (e.g., the users astrological
sign or income level). Another way to think about add-ons and extensions is that add-ons
work with MODX and extensions change MODX. Most o the components you might
install are add-ons. MODX is designed to make use o a wide variety o add-ons that can
use a combination o chunks, snippets, andplugins(more on these later in this chapter)
to do almost anything you want without altering MODX itsel.
For most MODX users, the difference between add-ons and core extensions is not impor-
tant. Users install components that meet their needs and dont really care about what
goes on under the hood. For advanced MODX developers, however, the difference is an
important one.
Even beginning users o MODX should know that components o all kinds are not offi cially
part o MODX. Tird-party components are contributed by volunteers o varying abilities.
Some are careully constructed and highly robust while others are less so. You should also
be aware o the term Sponsored Extras. Sponsored Extrasare third-party components
that have been created, edited, or reviewed by the MODX core programmers to assure
that they adhere to MODX coding standards and will not interere with the MODX core.
1|HowMO
DXWorks
4 MODX: The Offi cial Guide
-
8/10/2019 Modx Tog Sample
24/90
The Back End vs.the Front EndMODX is divided into two basic parts: the back end and the ront end. Te back endis
another name or the MODX Manager. Te font endis what visitors to your site see in
their browsers.
The Back EndTeMODX Manager(or back end) is where you do the main work o building and man-
aging your site. In theManager, you can create and edit content. You can also perorm a
whole array o administrative tasks such as creating users and controlling what those users
can do and see at the site. You can create administrative users who can share the workload
with you. You can also create and edit any o the various MODX objects such as resources
(including documents), templates, template variables, snippets, chunks, plugins, lexicons,
namespaces, categories, property sets, system settings, etc.
Tis list o MODX objects is ofen daunting or newcomers to MODX, but each o them
has a useul part to play in the development o your site, and together, theyll let you do
things with your site that you never thought possible. Teyll also make your lie as a web
developer much easier and more productive (trust me). Well cover each o them in depth,
and by the time you nish the book, you should be comortable with all the ones you need
or your site.
The Front EndTefont endis the part that visitors to your site see. Tere may be parts o your site that
only logged-in users can see, but afer logging in, theyre still in the ront end o the site.
Depending on how you set things up, ront-end users may still be able to add or edit site
content and perorm specic administrative tasks, but the key difference is that they are
not in theMODX Manager they are in thefont endo the site. Because they are not in
the Manager, what they can do is strictly limited (unless you create and implement code
that bypasses the restrictions). Tis protects the security o your site. It also lets users
contribute without learning the Manager interace.
MODX: The Offi cial Guide 5
-
8/10/2019 Modx Tog Sample
25/90
-
8/10/2019 Modx Tog Sample
26/90
-
8/10/2019 Modx Tog Sample
27/90
regular ont and capitalize the rst letter o each word in the eld name (Summary, Menu
itle, Long itle). When were talking about the specic eld in the database, well use
bold type, lowercase, and a different ont (introtext, menutitle, longtitle). Tere are
no capital letters in any eld name. Tis difference is not that important now, but will be
critical when we talk about setting these elds in later chapters.
n
In the book, well often refer to documents as resources (which they are). The
document is the default type of resource and the most often used, but it is notthe only one weblinks, symlinks, and static resources are also resources. So
all documents are resources, but not all resources are documents.
When users visit a web page at your site, the URL they are visiting is associated with a single
document. Te web page does more than just display the documents content, however.
It will usually also show the documents content embedded in the template associated
with that document (well discuss templates in the section below). It may also show the
documents itle or some o the other resource elds. I the document is not currently
published, the browser may not show it at all.
o complicate things slightly, a web page may be associated in various ways with more than
one document. It might show a document that contains the summary elds o a number
o other documents with links that will send the viewer to a ull version o each document.
A blog web page in MODX, or example, might show several different blog posts, each
listing the author and date. Each o those posts is the contenteld o a separate docu-
ment, and the author and date come rom the createdbyand createdonresource elds
o that particular document. Te summary presented or each item normally comes rom
the introtextresource eld.
Given the complex relationships possible here, you can see why its important to understand
that web pages and documents are very different things in MODX. When we talk about
documents in the book, were always reerring to the MODX document object created in
the Manager, not to a web page viewed by a site visitor. Well always reer to a single page
displayed in a browser as a web page.
Weblinks, Symlinks, and Static Resources
A weblinkis a MODX Resource that contains a URL (also called a link) in its contenteld.
With a weblink, the URL can be to a page at the MODX site or any other site on the Web.
1|HowMO
DXWorks
8 MODX: The Offi cial Guide
-
8/10/2019 Modx Tog Sample
28/90
In MODX, a linkcan be expressed as a ull URL like this:
http://yoursite.com/home.html
I, instead, it is a link to a page on your own MODX site, it can be expressed as a link tag
(e.g., [[~1]]). I your Home page is resource 1 on your site (in other words, its Resource
ID number is 1), MODX will replace the link tag with a ull URL that will take users to
your Home page.
You should use link tags whenever you can because they will take you to the same page
even i the title o the page changes or it is moved to another location in the Resource tree.
A symlinkis also a MODX resource that reers to another document, but the Symlink eld
contains only the Resource ID o the document being reerred to, and it must reer to a
page on the MODX site.
Te main use o weblinks and symlinks is to serve as links in a MODX menu. Tis is a
somewhat advanced topic, and well cover it in more detail later in the book.
Static resourcesare resources that contain a le path in their contenteld. Most MODX
pages have dynamic content because they contain elements, such as snippets and chunks,which may change over time. Tat means that the content o the page will be created on
the y beore being seen by the site visitor. When you have content that you know wont
change unless you edit it yoursel, however, you can save it as a le and use a static resource
to display it. Te page will display aster and will put less strain on MODX and the Database.
Static Resources may also contain links to les you want to deliver to the visitor such as
.PDF les or .DOC les or display or download. You can even use PHP code to create
dynamic .PDF les, or example, that the user can view or download by ollowing a link
to the static resource. Tis also allows you to control access to the les so that some users
can reach them and others cant.
Content ElementsContent elements(usually reerred to as just elements) in MODX are just what their name
suggests: they are MODX objects that create, control, ormat, organize, and/or contain
content. Te phrase content element is somewhat exible, and as MODX evolves, new
elements are created, and sometimes things that were ormerly resource elds may become
elements. Sometimes elements can lose that status and be reclassied as something else.
Te best working denition o content elements is: things that appear in the Element tree
on the Elements tab at the lef side o the MODX Manager.
MODX: The Offi cial Guide 9
-
8/10/2019 Modx Tog Sample
29/90
Te section below discusses the elements that existed at the time this book was written:
templates, template variables, chunks, snippets, plugins, and categories. You should be
aware, however, that a ew o them may not be ound in the Element tree in your version
o MODX.
Templates
Most businesses have a standard letterhead they use when sending letters. It gives everyletter the same look and saves time since the letter writer doesnt have to type the company
name, address, and telephone/ax numbers on each letter. A MODX templateperorms the
same unction. It contains the basic inormation that will appear on a number o different
web pages. It will usually contain the basic (X)HML or a web page (DOCTYPE, ,
, etc.) as well as the banner at the top o the page and the ooter at the bottom. It
may also contain other MODX objects, as well see in the section below.
Like the company letterhead, the template will probably contain a header and ooter (pos-
sibly with images) that will appear on every page that uses the template. Unlike a letterhead,
however, a MODX template can also contain other MODX objects. It might contain a
documents itle (and/or Long itle) and a menu. Tese will change on every page, butthey will always appear in the same place and with the same styling or every page that
uses that template.
When MODX receives a request or a web page rom a browser, it nds the appropriate
resource (usually a document), then checks to see what template is attached to that resource.
Te template contains (X)HML code interspersed with MODX tags. MODX retrieves the
template rom the database and begins lling it with the appropriate content (by replacing
the MODX tags) as the rst step in preparing the web page to be returned to the browser.
Beginning MODX users sometimes create more templates than they need because they
dont ully understand how exible MODX templates can be. Some MODX sites (but not
all) can get by with a single template even though there are things that will appear on some
pages but not others. Well look at templates in more detail later in the book.
Template Variables
emplate variable is a conusing phrase or some users because it hasnt always been
used consistently. Sometimes, the resource elds we discussed above (itle, Menu itle,
Alias, etc.) have been reerred to as template variables, even in the offi cial MODX docu-
mentation. Tis is incorrect, however. Tose things should be called resource elds.
Template variablesare always created by a user who needs additional resource elds.
1|HowMO
DXWorks
10 MODX: The Offi cial Guide
-
8/10/2019 Modx Tog Sample
30/90
emplate variables (ofen called TVs or short) provide a way o extending the list o
resource elds. Imagine that you let registered users create some content on your site.
When a page created by a user is displayed, you could show the documents itle and the
date it was posted by using the documents pagetitleand createdonresource elds. What
i you also wanted to show the authors astrological sign? You need another resource eld.
Luckily, you can easily add a V called Sign to hold that inormation (well talk about
exactly how to do this in a later chapter). Now, when someone edits the document in the
MODX Manager, theyll see an extra eld labeled Sign with a blank space or entering
the users astrological sign.
emplate Variables are very exible and can be used to hold many things such as text, images,
(X)HML code, dates, directory contents, etc. In act, we could easily present our Sign
V as a drop-down list o the twelve astrological signs or as twelve radio buttons. Tis is
quite easy to do in MODX, and well discuss how later in the book.
At this point, you might be wondering how the content o the Sign V gets on the web
page. Te easiest way is just to place a resource tagin the template associated with that
document (well discuss tags in more detail later in this chapter). A resource tag looks like
this: [[*Field/TvName]]. Both template variables and resource elds can be displayed
using resource tags. Te ollowing code in the template would display the title, date, andsign, on the page:
Post Title: [[*pagetitle]]
Created on: [[*createdon]]
Author's sign: [[*sign]]
emplate variables are a powerul and underused part o MODX. Tey can hold strings
o text, such as a persons sign, but they can also hold other objects you might want to
put on a web page such as drop-down lists, date pickers, and even the content rom other
documents on the site. Well talk about how to create them and use them in more detail
later in the book.
Chunks
A MODX chunkis just a piece o reusable content. Te key thing to remember about chunks
is that they cant contain raw PHP code (thats the job o snippets). Many chunks are just
bits o content embedded in (X)HML code that you want to appear on multiple pages.
Te banner at the top o a page, the ooter at the bottom, and the menu are ofen contained
in chunks. Tat way, i you edit the chunk, it changes things on every page.
MODX: The Offi cial Guide 11
-
8/10/2019 Modx Tog Sample
31/90
Special-purpose chunks called pl chunks are used as mini-templates. Tey usually contain
text and placeholder tags (more on those later) and are used ormat output. Here is a simple
example that could be used to display the name o the current president and vice-president
o a company:
Officers
President: [[+president]]
Vice-president: [[+vice-president]]
ypically, code in a snippet would set the values or the two placeholder tags above so that
the appropriate names would appear when the chunk is rendered.
pl chunks are also used or web orms and as mini-templates or the output o standard
add-on components. pl chunks are sometimes reerred to as templates, but this is
incorrect.
Te content o a chunk makes it into a page in various ways. Te most common method or
displaying chunks is to put a chunk tagin the template or the contenteld o a document.
A chunk tag looks like this: [[$ChunkName]]. Well see some other methods o injecting
chunk content later in the book, and well discuss tags in general a little later in this chapter.
Snippets
A snippetis simply a piece o executable PHP code. I your users can submit content (such
as blog comments) that immediately appears on the site, what happens i a malicious
user puts PHP code that erases your hard disk in a comment? In an unprotected site, the
rst time someone visits the page that shows that comment, its goodbye site. In MODX,
however, nothing happens at all because PHP code in a pages content is stripped out. o
be executed, the code must be in a snippet. What appears in the page content, then, is the
snippet tag(sometimes called a snippet call). A snippet tag looks like this:
[[SnippetName]]
or
[[SnippetName? &firstName=`John` &lastName=`Doe`]]
In the second example above &firstNameand &lastNameare just pieces o inormation
called snippet properties(ormerly called parameters)that we want to send to the snippet
being called. Whatever is returned or printed by the snippet will replace the snippet tag
in the page sent to the browser or display.
1|HowMO
DXWorks
12 MODX: The Offi cial Guide
-
8/10/2019 Modx Tog Sample
32/90
nImportant: Note that the values of the snippet properties are enclosed
in back-ticks, not single-quotes. This allows you to use single- and
double-quotes in your snippet properties (e.g., &lastName=`O'Connor ). The
back-tick is under the ~ at the upper-left on most keyboards.
Using single-quotes, double-quotes, or nothing at all around snippet properties is the most
common error made by new users o MODX. I you do that, your snippet simply wont
work. Other common errors are orgetting the question mark afer the snippet name or
the ampersand beore every snippet property, and misspelling the name o the snippet
or a snippet property (the names are case-sensitive, so type careully). One last common
snippet error to check or is that a Rich ext Editor like inyMCE may be changing the
ampersands in your snippet tags to the & entity every time you save your work. o
x this, click on the HML button in the editor and convert &or &&to a
single ampersand character inside snippet tags.
nAlthough we often put spaces around equal signs in PHP code to improve
readability, we dont do it with snippet tags because it can confuse the parser
in some older versions of MODX Evolution.
Well discuss snippets and snippet tags in detail later in the book. I you dont know PHP,
you wont be writing or editing snippets, but youll still need to understand a little bit about
how snippets do their jobs and how to work with snippet properties.
Many beginning MODX users know no PHP at all and have no intention o learning it. Some
o them are able to create very sophisticated MODX sites without using PHP code. Many
others, however, learn PHP gradually as they continue to use MODX, and some becomequite good at it and begin writing their own snippets and plugins. As we said earlier, PHP
is not a diffi cult language, and there is a short MODX PHP Primer at the end o the book
to get you started. One o the great things about MODX is that no matter how much you
know, theres always more to learn.
Plugins
Plugins are kind o an anomaly among the MODX elements. Tey ofen alter content, but
you dont display them on a web page using tags. Plugins are used to interrupt the pro-
cessing o the MODX engine and add custom unctions.
MODX: The Offi cial Guide 13
-
8/10/2019 Modx Tog Sample
33/90
Tere are a number o hooks into the MODX engine (called system events) that let you
perorm just about any kind o operation at key points in the processing. As MODX goes
about its job, it periodically res one o a number o system events. Tere are events that
re just beore a page is rendered in the browser, just afer a user attempts to log in, and
just beore a document or user is saved in the Manager, or example. Each system event has
a name, and MODX plugins can listen or a particular system event and act when it res.
Aplugin, then, is just a bit o PHP code that listens or a particular system event. When
that event res, the plugins code executes. For example, a plugin can give you accessto a documents content just beore it is rendered as a web page by having it listen or the
OnWebPagePrerenderevent. You could translate the documents content, emphasize key
words, strip out HML comments, turn some items into hyperlinks, etc.
You can also use a plugin to process documents beore theyre saved in the Manager, process
a users inormation during the process o logging in, or do any number o other transor-
mations. Plugins are written in PHP code, and you can do anything with them that you
can write code or.
Te beauty o plugins is that they allow you to put custom processing in place without
hacking the MODX core. Tat means your work will be unaffected by upgrading to newer
versions o MODX. Because o the many built-in ways o expanding and extending MODX,
you can do almost anything you can think o without touching the MODX core code.
Categories
Categoriesare basically just labels that you can apply to elements to help you organize them
and control access to them. When you create or edit a snippet, plugin, chunk, template,
or template variable, you can assign it to an existing category or create a new category or
it. When that element is shown in the Element tree in the Manager, it will appear below
its category name.
In MODX Revolution, you can assign elements to categories by dragging and dropping
them onto the category older at the bottom o the Element tree.
Note that categorized elements will not show in the Category section o the tree (even
though thats where you dragged them). Instead, theyll show under a category older in their
respective sections. For example, a snippet added to the category MyCategory will appear
in the Element tree in a MyCategory older that appears in the Snippet section o the tree.
nResources and files dont have categories. Resources in the Resource tree are
organized into a hierarchy under their respective parents and files are orga-
nized by the physical directories in which they are stored.
1|HowMO
DXWorks
14 MODX: The Offi cial Guide
-
8/10/2019 Modx Tog Sample
34/90
You can have as many categories as you like, and you can have categories within categories.
You might, or example, have a category calledMyChunksto keep the chunks you create
separate rom the ones used by various MODX components. I you create a lot o chunks,
you might have subcategories under MyChunks.
Once elements are placed in a category, you can hide them or control what users can do
with them by creating Element Category Access ACL entries in the Manager (see Chapter
10 or more details on MODX security).
I you dont use categories to control access to elements, they are just there or your con-venience in organizing your elements and making them easier or you to nd when you
want to edit them. Categories are completely optional. Some people dont use them at all.
Others, especially those with very complex sites, use lots o them. As with so many things
in MODX, its up to you.
Other ElementsTe ollowing elements are not ound in the Element tree, but they serve to store and
present content on your site. Tey include placeholders, links, settings, tags, and les.
Placeholders, Links, and Settings
Placeholdersare not shown in the Element tree in the Manager, but they qualiy as ele-
ments because they hold content and can be displayed using resource tags. Te reason
they dont show in the Element tree is that their value is always set in snippets or plugins
rather than being entered in the Manager. A snippet or plugin sets a placeholder by using
the ollowing bit o PHP code:
$modx->setPlaceholder('placeholderName','value');
Once the placeholder has been set, its value will replace any instance o the corresponding
placeholder tag:
[[+placeholderName]]
Many MODX snippets set placeholders. You can display the values set or those placeholders
with placeholder tags. Te tags can go in a resources content eld, in a chunk, or in a tem-
plate variable or template. I you have a snippet (lets call it SetAuthor), or example, that
sets a placeholder called author_nameto the name o the author o the current document,
MODX: The Offi cial Guide 15
-
8/10/2019 Modx Tog Sample
35/90
you could put the ollowing snippet tag in your template: [[SetAuthor]]. Te snippet
tag would produce no output because your snippet neither prints anything nor returns
anything it just sets the placeholder. Anywhere in the content o your document, then,
you could insert a placeholder that would be replaced by the authors name:
The author of this document is [[+author_name]].
Note that or the [[+author_name]]tag to work, the snippet tag must come beore it in
the code so that the placeholder will be set.
MODX does set a couple o placeholders or you on every page request that you can use
to display the ID or username o the currently logged-in user (i any).
ID of the current user: [[+modx.user.id]]
Username of the current user: [[+modx.user.username]]
Linksare a MODX shorthand or a URL to a page at the site and are based on one o the
resource elds theResource ID. Most o the time, links are used to reer to documents.
Te Resource ID o a document is sometimes called the document ID or document identier,
but the correct term is Resource ID. Te ID is shown in parentheses in the Resource treein the Manager ollowing the resources name. You can place a link pretty much anywhere
by using the link tag:
[[~##]]
In the code above, you would replace ##with the Resource ID o the resource (document)
you want a link to. Tat may sound complicated, but its really pretty simple. Lets look at
an example. Suppose you have a page about aardvarks that has a Resource ID o 12. You
would see the number 12 in parentheses next to the name o the document in the Resource
tree (on the Resources tab) in the Manager. Anywhere you would put http://mysite.com/aardvark.html, you could put [[~12]]instead. Te name o the document might
change, and its location on your site might change, but [[~12]]will always provide a reli-
able link to it because its Resource ID will never change. You should always use a link tag
when creating a link to any page at your site.
1|HowMO
DXWorks
16 MODX: The Offi cial Guide
-
8/10/2019 Modx Tog Sample
36/90
Like placeholders, settings dont show in the Element tree but can be displayed using tags
(setting tags, to be precise). A settingis essentially a variable whose value is available across
the MODX site. Tey include system settings, context settings, and user settings (more on
these later in this chapter). All are displayed with a setting tag:
[[++setting_name]]
You can use setting tags reely to display or use the values o any system, context, or user
settings. Some system settings are critical to the operation o MODX, however, so dontchange a system setting unless youre sure o what it does.
Tags
Weve already seen some MODX tagsin this chapter, but lets look at them a little more
closely. All MODX tags are replaced by the object they represent. Here is a quick list
showing what each tag will be replaced by:
Chunk tag Contents o the chunk
Resource tag Value o the resource eld or template variable it represents Snippet tag Output or return value o the PHP code in the snippet
Link tag Te URL o the resource it reers to
Placeholder tag Te value o the placeholder (ofen set in a snippet or plugin)
Setting tag Te value o the context, user, or system setting
Language tag A particular language string rom the current lexicon
In MODX Revolution and beyond, all tags begin with [[and end with ]]. Weve discussed
most o the tags, but able 1-1 gives a summary o the new tag style used in MODX Revolu-
tion and later and the tags used in earlier versions o MODX:
Table 1-1: Old and New Tag Styles
Tag Type MODX Evolution (old) MODX Revolution
Resource [*ResourceField/TvName*] [[*ResourceField/TvName]]
Chunk {{ChunkName}} [[$ChunkName]]
Snippet [[SnippetName]] [[SnippetName]]
Setting [(SettingName)] [[++SettingName]]
Placeholder [+PlaceholderName+] [[+PlaceholderName]]
Link [~ResourceId~] [[~ResourceId]]
Language No ag [[%LanguageStringKey]]
Note that those symbols afer the opening braces ($, +, ++, *, ~, and %) are called tokens
in MODX. Tey tell MODX what kind o tag is being processed.
MODX: The Offi cial Guide 17
-
8/10/2019 Modx Tog Sample
37/90
New users o MODX ofen dont realize that tags can be used almost anywhere in MODX
and that you can nest them. A snippet tag can contain a chunk tag as a property, and the
chunk could contain resource tags that might contain link tags.
Heres an example o a setting tag nested inside a link tag. It will display a link to the sites
Home page:
[[~[[++site_start]]]]
Lets break that down and look rst at the outer tag, which is a link tag.
[[~X]]is a link tag whereXis the Resource ID o the document you want to link to. It will
be replaced by the URL associated with that document. In other words, the tag [[~12]]
will be replaced by the URL o the document whose Resource ID is 12.
nThere is nothing special about the Home page of a MODX site. The site_start
system setting can point to any page on the site and MODX treats the page like
any other when it is rendered.
[[++site_start]]is a setting tag that will be replaced by the Resource ID o your sites
Home page. So i the Resource ID o your sites Home resource is 1 (and it ofen is), this
tag will be replaced by the number 1.
So [[~[[++site_start]]]]will be replaced by [[~1]]which will be replaced by some-
thing like http://yoursite.com/home.html. For an actual link to your Home page,
youd want something like the ollowing (X)HML code:
Home
tWhen creating nested tags in MODX, always count the number of left and
right brackets. The two numbers must be equal, and in MODX Revolution,
each must be an even number.
1|HowMO
DXWorks
18 MODX: The Offi cial Guide
-
8/10/2019 Modx Tog Sample
38/90
For the more technically minded, here is a specication o the MODX tag syntax:
[[ opening brackets.
! (optional) do-not-cache ag.
elementToken token identiying the element type i its not a snippet:
no token snippet.
$ chunk.
* resource eld/template variable (V).+ placeholder.
++ setting.
~ link.
% language.
elementName name o element (e.g., Waynder, MyChunk).
@propertysetName (optional) property set identier.
:modifierName=modifierData`: (optional) one or more output modiers.
? indicates that properties are coming; required i there are properties.
&propertyName=propertyValue` & properties prexed with &
]] closing brackets.
Here is a complex tag example with every possible type o tag element:
[[!getResources@propset1:default=`No resources found.`? &parents=`1`
&sortby=`RAND()`]]
Te tag above tells MODX to process the getResources snippet uncached speciying
propset1to override the deault properties. Te :defaultoutput modier will produce
a message i getResources returns nothing. wo properties,&parentsand &sortbywill
be sent to the snippet and will override any other properties with the same names.
FilesIn MODX,lesare simply les that exist within the MODX site. As weve seen in the sec-
tions above, much o the content and ormat o a MODX web site is contained in docu-
ments, chunks, templates, and other MODX objects that exist in the MODX database. Files
still play a role, however. You will probably have some les o your own. You might have
image les, CSS les, JavaScript les, or other les that are used in your site. In addition,many MODX components have readme.txtles, class les, CSS les, example les, etc.
MODX: The Offi cial Guide 19
-
8/10/2019 Modx Tog Sample
39/90
Te les used by components are generally ound in one o two places. Files that need to
be web-accessible are located below this directory (where component_nameis the name
o the component):
assets/components/component_name
Files that dont need to be web-accessible are located below this directory:
core/components/component_name
Te les or the Waynder snippet, or example, will be in these two directories:
assets/components/wayfinder/
core/components/wayfinder/
In MODX Revolution, the /coredirectory containing all o the critical MODX PHP les can
be located outside o the public_htmldirectory so that its les cant be accessed directly
rom the Web. Tis makes MODX much more secure. A good security principle or les
is that les containing executable code (e.g., executable PHP les) or sensitive materiallike Social Security Numbers should go under the relocated /coredirectory so they cant
be reached directly via the Web.
New users o MODX are ofen conused about where to put their own les. Te offi cial
MODX answer is an emphatic, but somewhat unhelpul, anywhere you want. It is a guiding
principle o MODX not to restrict users in any way unless its absolutely necessary or MODX
to unction correctly (and MODX is designed so that there are very ew restrictions). As
long as you know where the les are and you tell MODX where they are, anything goes.
Some users like to put the les in, or just under, the root directory or aster loading in
/images, /css, /js, etc. Another good place to put them is somewhere under the MODX
/assetsdirectory (i.e., assets/images, assets/css, assets/js). Properly writtenthird-party components always reer to the assets directory by the MODX_ASSETS_PATH
setting, which you can set.
Te /assetsdirectory is never used directly by the MODX core. Because o the way the
/assetsdirectory is handled by MODX, you can be condent that it wont be touched
when you upgrade your MODX installation to a new version. I all o your personal les
are below the /assetsdirectory, you can be certain that they wont be touched by an
upgrade. Placing them there also makes it possible to rename, relocate, or re-upload the
other MODX directories without worrying about your own les.
1|HowMO
DXWorks
20 MODX: The Offi cial Guide
-
8/10/2019 Modx Tog Sample
40/90
How MODX Deliversa Web PageNow that you have some sense o the basic building blocks MODX uses to create a web
page, lets look briey at how MODX does the job.
When a users browser requests a web page rom the site, MODX rst checks to makesure that the page exists. I it does not, the user is orwarded to the sites Error(page not
ound) page. Next, MODX checks to make sure that there are no security restrictions that
would prevent the current user rom viewing the page. I there are, the user is orwarded
to either the Errorpage, or the sites Unauthorizedpage (depending on the security set-
tings) and processing stops.
Assuming that there are no security restrictions that would prevent the user rom seeing
the page, MODX retrieves the document associated with that URL and checks to see
what template is associated with that document. It then gets the template, and the MODX
document parsergoes to work.
Te document parser loads the template into its own internal text editor. Te template
will contain tags identiying the various building blocks. Te document parser replaces
those tags with the things they represent. For example, a chunk tag will be replaced by
the contents o the chunk and a snippet tag will be replaced by the output o the snippet.
Once that replacement has been made, there may be some tags lef in the page (the chunk
might contain some tags, or the snippet might put some tags in the output it returns). Te
snippet might also pull content rom another snippet or chunk or rom a le and insert it
into the output it returns.
Te parser continues replacing tags until there are no more lef. I any plugins are listening
or the events that re during this process, they may also alter the page content at variouspoints in the process. In addition, i some o the content is cached, the parser will get the
content rom the MODX cache instead o the database. When the process is complete
and there are no more tags to process, MODX delivers the page to the web browser or
display. I the resulting page contains a reerence to a le to be included (such as a CSS
le, a JavaScript le, or an image le), the browser will handle that appropriately and then,
nally, show the page to the user.
MODX: The Offi cial Guide 21
-
8/10/2019 Modx Tog Sample
41/90
Transport Packagesransport packages are new in MODX Revolution and are one o the best reasons to upgrade
to the new version. A transport packageis a .ZIP le that can contain les, MODX objects,
and PHP scripts packaged or automatic installation in a MODX site. Te most common
transport package is used to install a specic third-party component, but transport pack-
ages can contain core extensions, updates, templates, simple collections o les, or even
an entire MODX site.
In earlier versions o MODX, in order to install a third-party component, you needed
to download the component, unzip the les in the appropriate directory at the MODX
site, create elements, and cut-and-paste code rom the component les into the elements.
Sometimes the process was not very well-documented and it was easy to make mistakes
that would make the component unusable. With ransport packages, you go to Package
Management in the MODX Manager, search or available packages, download them, and
click on Install. All the work is done or you and done without errors.
Even better, ransport packages can interact with the user during the install process, so
you can ofen set congurations and preerences during the install. Te SPForm package,o