On March 26, 2019 we launched new MODX Forums. Please join us at the new MODX Community Forums.
Subscribe: RSS
  • Hi,

    I’m working on my first MODx website (loving MODx by the way) which will use a number of snippets.

    I’m looking for guidelines, tutorials, worked examples etc on writing snippets but the obvious Google searches haven’t found anything that is a full step by step guide to writing snippets ’properly’.

    The hints on the MODx Wiki page: http://wiki.modxcms.com/index.php/Creating_Snippets give some good pointers but what I’m looking for is a detailed worked example. In particular, I’d like it to explain what is generally thought to be the best approach on the use of chunks and placeholders to separate layout from the PHP code in the snippet. Point 2.11 in the wiki article gives a hint as to how it should be done ... but a worked example would make it so much easier to understand.

    So, anyone know of such documentation on the web (or anyone willing to write it)?

    Cheers,

    Colin
    • The "proper" way to develop snippets will depend on your objectives.

      To set a placeholder you use the setPlaceholder API function as explained in the wiki post:

      <?php
      // do some logic to get the placeholder value
      $value = "MODx";
      
      // define the placeholder and set it's value
      $modx->setPlaceholder('placeholderName',$value);
      
      ?>


      Then in the document you could use the [+placeholderName+], but you need to place the snippet call on the document (or in the template) in order have the placeholder set:

      My favorite CMS is [+placeholderName+]!

      As for the chunk, you have several options for doing this:

      1) You could simply place the chunk with the placeholder in the document content and let the MODx document parser handle the placeholder.

      2) You could use the parseChunk API function to parse out the placeholders in the chunk and then output the parsed chunk:

      <?php
      // do some logic to get the placeholder value
      $firstName = "John";
      $lastName = "Smith";
      
      // define the placeholders and set their values
      $modx->setPlaceholder('firstName',$firstName);
      $modx->setPlaceholder('lastName',$lastName);
      
      // set chunk name in this example it is named addressBook
      $myChunk = "addressBook";
      
      // parse the chunk and replace the placeholder values.
      // note that the values need to be in an array with the format placeholderName => placeholderValue
      $values = array('firstName' => $firstName, 'lastName' => $lastName);
      
      // run the parseChunk function
      $output = $modx->parseChunk($addressBook, $values, '[+', '+]');
      
      return $output;
      
      ?>


      This will output the parsed chunk where the snippet is placed on the document.

      Note: alternatively you could set the output to be a placeholder as well by removing the return statement and replacing it with a setPlaceholder function call:

      <?php
      
      //.… all the code above
      $output = $modx->parseChunk($addressBook, $values, '[+', '+]');
      
      // return $output;
      
      $modx->setPlaceholder('output',$output);
      
      ?>


      And then you would place the [+output+] placeholder where you want it to appear on the document.

      3) you could use the getChunk API function together with the str_replace php function. This is a bit more code but can be more efficient depending on your objective. For example Ditto uses this method in a function:
      <?php
      // example from Ditto template.class.inc.php
      	// ---------------------------------------------------
      	// Function: replace
      	// Replcae placeholders with their values
      	// ---------------------------------------------------
          function replace( $placeholders, $tpl ) {
      		$keys = array();
      		$values = array();
      		foreach ($placeholders as $key=>$value) {
      			$keys[] = '[+'.$key.'+]';
      			$values[] = $value;
      		}
      		return str_replace($keys,$values,$tpl);
      	}
      
      ?>


      Hope this gets you started.
        [font=Verdana]Shane Sponagle | [wiki] Snippet Call Anatomy | MODx Developer Blog | [nettuts] Working With a Content Management Framework: MODx

        Something is happening here, but you don&#39;t know what it is.
        Do you, Mr. Jones? - [bob dylan]
      • This doesn’t answer your question, but you may find something useful here: http://bobsguides.com/modx-snippet-faq.html.
          Did I help you? Buy me a beer
          Get my Book: MODX:The Official Guide
          MODX info for everyone: http://bobsguides.com/modx.html
          My MODX Extras
          Bob's Guides is now hosted at A2 MODX Hosting
        • Thanks to those who replied. I’ve got my snippets using placeholders and chunks successfully smiley

          I understand that the ’right’ way to produce output from a snippet is to use chunks that use placeholders to define the generated HTML.

          My next question is: What approaches are used to specify a default text for a chunk that is used by a snippet?

          Consider ... if a snippet is using parseChunk then the named chunk must have been setup via the manager for the snippet generate any output. In terms on installing the snippet on a site, this means the admin has to manually create the chunks and cut & paste in some default text for them. It would be nice if the snippet code could come with default text for the chunks. However, the putChunk API method has been deprecated so there appears to be no way for the snippet code to put the default text of a chunk into MODx.

          The only way I can see of solving this is to
          + if getChunk finds a (non-default) text for a chunk then use that
          + else use the default text of the chunk (from an array in the snippet)
          + use str_replace to fill in the values of any placeholders in the chunk text

          Is this right? Have I missed something?

          Cheers,
          • I don’t really understand your question, but maybe this will help.

            Typically, a default chunk (or multiple default chunks) is/are created when the snippet is created. If the user sends the name of a chunk to use as a parameter in the snippet tag, that chunk is used. If not, the snippet uses the default chunk.

            [!snippetName!]


            or

            [!snippetName? &tplChunk=`MyChunk`!]


            Then in the snippet:

            <?php
            if (empty($tplChunk)) { 
              $tplName = 'defaultTpl';
            } else {
              $tplName = $tplChunk;
            }
            ?>


            As an alternative, the "default chunk" content is sometimes kept in a file or coded directly into the snippet (if it’s short).
              Did I help you? Buy me a beer
              Get my Book: MODX:The Official Guide
              MODX info for everyone: http://bobsguides.com/modx.html
              My MODX Extras
              Bob's Guides is now hosted at A2 MODX Hosting
            • Wayfinder and Ditto are two prime examples of flexible configuration and templating. You can examine them to see how it is done.
                Studying MODX in the desert - http://sottwell.com
                Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                Join the Slack Community - http://modx.org
              • Thanks for the replies (sorry for late reply - been offline for a few weeks).

                Bob’s reply answered by question:

                As an alternative, the "default chunk" content is sometimes kept in a file or coded directly into the snippet (if it’s short).

                Thanks all,

                Colin