Creating Symlinks in Code

Using PHP code to create a new Symlink


In the last article, we discussed the differences between Symlinks and Symlinks. In this one, we'll look at how to create a Symlink in code.


MODX logo

Creating Symlinks

Creating a new Symlink in code is fairly simple, and very much like creating a Weblink. We create the new object, set a few of its fields, and save it. For the content field, we'll use the variable $content because it goes in the content field. For a Symlink, it should always be a Resource ID.

Remember that a resource ID will not work on MODX versions before 2.2.5. Also, don't forget to capitalize the "L" in modSymLink.


The Code

/* Symlink creation code */

/* Set this to the ID of the resource you want to link to */
$content = 12;

$symlink = $modx->newObject('modSymLink');
$symlink->set('content', $content);
$symlink->set('class_key', 'modSymLink');
$symlink->set('pagetitle', 'My Page');
$symlink->set('menutitle', 'My Page');
$symlink->set('alias', 'my-page');

$symlink->save();

Because we're setting a number of fields for the Symlink, you might be tempted to use this code for the creation of the Symlink:

$fields = array(
    'content' => $content,
    'class_key' => 'modSymLink',
    'pagetitle' => 'My Page',
    'menutitle' => 'My Page',
    'alias' => 'my-page',
);
$symlink = $modx->newObject('modSymLink', $fields);

$symlink->save();

For some MODX objects, this will work, but it often fails. For Symlinks, not all of the fields will be set if you do it this way. Fortunately there's another way, and you can use it any time you're setting multiple fields on a new MODX object.

$fields = array(
    'content' => $content,
    'class_key' => 'modSymLink',
    'pagetitle' => 'My Page',
    'menutitle' => 'My Page',
    'alias' => 'my-page',
);
$symlink = $modx->newObject('modSymLink');
$symlink->fromArray($fields);

$symlink->save();

Using fromArray() to set the new object's fields is much more reliable, and it will work with any MODX object because fromArray() is a method of xPDOObject. All MODX objects are descendants of xPDOObject, so they will always have the fromArray() method.

The fromArray() method has a number of additional arguments, but for this use case, the defaults for those arguments are exactly what you want.


Coming Up

In the next article, we'll see how to update an existing Symlink in code.



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 A2 hosting. (More information in the box below.)



Comments (0)


Please login to comment.

  (Login)