Updating a Weblink in Code

How to change the page that a Weblink points to


You might someday want to modify a Weblink in code, using either a snippet or a plugin. You might, for example, want to set the link the Weblink points to based on the value of some TV or System Setting. In fact, that exact problem asked by MODX Forum user Devlanda inspired this series of articles. In this one, we'll look at how to update an existing Weblink to point somewhere else.


MODX logo

Getting the Weblink Object

As you might guess, updating an existing Weblink is very similar to creating one, you just have to get the modWebLink object, set any fields you want to change, and then save it.

You can retrieve the Weblink 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 Weblink in the Resource tree), like this:

$pageId = 12; /* Set this to the ID of the Weblink */
$webLink = $modx->getObject('modWebLink', $pageId);

Don't forget to capitalize the "L" in modWebLink.


Updating the Weblink

In this example, we'll just change the Weblink to point to a different page (Resource ID 22):

$webLinkId = 12; /* Set this to the ID of the Weblink itself */
$newPageId = 22; /* ID of the new page to be linked to */

/* Get the WebLink Object */
$webLink = $modx->getObject('modWebLink', $webLinkId);

if ($webLink() {
    $webLink->set('content', $newPageId);
    $webLink->save();
} else {
    $modx->log(modX::lOG_LEVEL_ERROR, 'Could not retrieve Weblink with ID ' . $webLinkId);
}

We set the content field because that always contains the Resource ID or URL the Weblink links to. Note that we could also have set a URL there. That would be necessary if the page you're linking to is not on your site. You might, for example, be getting the new URL from a web search engine or some other process. In that case we'd just change the $content value like this:

$content = 'https://somesite.com/somepage.html';

Other Fields

You can change any of the other fields of the Weblink (with one exception) by calling the Weblink's set() method. You could change the pagetitle, alias, menutitle, pub_date, or any other field this way *except* the responsecode field:

$webLink->set('pagetitle', 'newpagetitle');

If you want to change the responsecode field, you need to do it with a different call (as we saw in the previous article):

$webLink->setProperty('responsecode', 'HTTP/1.1 301 Moved Permanently');

Coming Up

In the next article, we'll look at Symlinks and the similarities and differences between Weblinks and Symlinks.



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.

  (Login)