You might someday want to modify a Symlink in code, using either a snippet or a plugin. You might, for example, want to set the link the Symlink points to based on the value of some TV or System Setting. In this article, we'll look at how to update an existing Symlink to point somewhere else.
Getting the Symlink Object
As you might guess, updating an existing Symlink is very similar to creating one, you just have to get the modSymLink
object, set any fields you want to change, and then save it.
You can retrieve the Symlink object by any field — pagetitle, alias,
menutitle, etc., but the fastest and most reliable method is to use its ID (shown in parentheses next
to the Symlink in the Resource tree), like this:
$pageId = 12; /* Set this to the ID of the Symlink */
$symLink = $modx->getObject('modSymLink', $pageId);
Don't forget to capitalize the "L" in modSymLink.
Updating the Symlink
In this example, we'll just change the Symlink to point to a different page (Resource ID 22):
$symLinkId = 12; /* Set this to the ID of the Symlink itself */
$newPageId = 22; /* ID of the new page to be linked to */
/* Get the Symlink Object */
$symLink = $modx->getObject('modSymLink', $symLinkId);
if ($symLink() {
$symLink->set('content', $newPageId);
$symLink->save();
} else {
$modx->log(modX::lOG_LEVEL_ERROR, 'Could not retrieve Symlink with ID ' . $symLinkId);
}
We set the content field because that always contains the Resource ID the Symlink links to.
Other Fields
You can change any of the other fields of the Symlink by calling the Symlink's
set() method. You could change the pagetitle, alias, menutitle,
pub_date, or any other field this way.
$symLink->set('pagetitle', 'newpagetitle');
Coming Up
In the next two articles, we'll look at a couple of advanced Symlink techniques.
For more information on how to use MODX to create a web site, see my web site Bob's Guides, or better yet, buy my book: MODX: The Official Guide.
Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at Hosting.com (formerly A2 Hosting). (More information in the box below.)

Comments (0)
Please login to comment.