We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 18266
    • 23 Posts
    Hello everybody!

    It started as a joke in Twitter, but here we go: My First Snippet. Please post your first, and please only your first snippet ever. If you like, write some lines about your personal why´s and how´s as well. I´ll post my own first one soon, too.

    All the best!
    Marcus
      • 4172
      • 5,888 Posts
      Hi Marcus,
      nice Idea. Did a quick search at the German modx-Forum. I think this was my first modx-snippet, I had posted there.
      I needed radiobuttons in my eForm-Form where I could choose webgroups to send eMails to.

      snippet ’eFormEvent’:

      <?php
      //functions for eForm events
      function createMailList( &$fields ){
      global $modx;
      $smarray=array(
      'webGroup'=>$fields['group'],
      'field'=>'email');
      $fields['email']=$modx->runSnippet('showmembers',$smarray);
      echo $fields['email'];
      echo $fields['group'];
      //return succes
      return true;
      }
      //return empty string
      return '';
      ?>
      


      my form:

      <p>Empfänger</p>
      <input type="hidden" name="formid" value="mailForm" />
      <input type="radio" name="group" value="mitglieder" checked="checked"><strong>Alle registrierten Mitglieder</strong>
      <div class="namelist">[[ShowMembers? &webGroup=`mitglieder` ]]</div>
      <input type="radio" name="group" value="vorstandsmitglieder"><strong>Vorstand</strong>
      <div class="namelist">[[ShowMembers? &webGroup=`vorstandsmitglieder` ]]</div>


      snippet-call:

      [[eFormEvent]]
      [[eForm? &formid=`mailForm`&tpl=`eMailForm`&eformOnBeforeMailSent=`createMailList`&report=`eMailReport`&sendirect=`1`&thankyou=`eFeedbackThanks`&debug=`0`]] 


      I added the parameter &field to showmembers for that, to get the field ’email’, for example, from members.
        -------------------------------

        you can buy me a beer, if you like MIGX

        http://webcmsolutions.de/migx.html

        Thanks!
        • 3749
        • 24,544 Posts
        I’m not sure, but I think this was my first snippet (never got around to creating a CRUD snippet out of it):

        <?php
        /*
        ::::::::::::::::::::::::::::::::::::::::
         Snippet name: ShowMetaData
         Short Desc: Displays db table metadata
         Version: 0.5
         Author: Bob Ray
         Date: May 7, 2007
        ::::::::::::::::::::::::::::::::::::::::
        Description:
         Shows the metadata (table structure) of a table in the MODx database.
         I wrote this as a quick and dirty way to look at the structure of any 
         table in the database. 
        
         I'm hoping to create a generic snippet that will
         allow front-end editing of tables in the database.
         I did this as a first step but thought it might be
         useful, or at least instructive, for others.
        
        
        ::::::::::::::::::::::::::::::::::::::::
        Example Usage:
            [!ShowMetaData? &tableName=`modx_active_users`!]
            
            The table name is just the name of the database
            table you want to see the structure of.
        
            Note: $tableName is a required parameter and must be
                  surrounded by backticks, not single quotes.
        
        
            To use this snippet, just paste this code (minus the php tags)
            into a new snippet called ShowMetaData. Then create a new document
            with the snippet call: [!ShowMetaData? &tableName='name of your table'!]
        ::::::::::::::::::::::::::::::::::::::::
        */
        
        
        //Check for $tableName parameter
        
        if (!isset($tableName)) {  
            
            return 'Error: No table name in Snippet call.<br>
            Example: [!showMetaData? &tableName=`mydbtable`!]<br>';
        }
        
        // Get the metadata from the MODx db
        
        $structureArray = $modx->db->gettablemetadata($tableName);
        
        echo '<h2>Structure of table: ',$tableName,'</h2>';
        
        // Raw view of structure
        // Comment out the following two lines if you don't want raw view
        
        echo '<h3>Raw View</h3>';
        print_r(array_values($structureArray)); //prints raw table structure
        
        
        
        echo '<h3>Prettified View</h3>';
        
        reset($structureArray); //may not be necessary but can't hurt
        
        while (list($key, $val) = each($structureArray)) // walk through fields
          {
          echo "<b>$key</b>";echo "<br />";   // field header
        
             while (list ($newkey, $newval) = each($val)) { //walk through each field's specifiers
                echo "<span style='color:#ff0000;'>   <b>$newkey:</b></span> $newval";
                echo "<br />";
             }
          
          echo '<p> </p>';  //separate the fields
          }
          echo "Note: If Null: is not YES then field doesn't allow null values.";
        ?>
          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
          • 20413
          • 2,877 Posts
          I think this is the one
          [!Year!]
          <?php
          // get the current time and apply the offset
          $timestamp = time() + date_default_timezone_set('America/Los_Angeles');
          // Set the current year
          $today_year = date('Y',$timestamp);
          
          print $today_year;
          ?>

            @hawproductions | http://mrhaw.com/

            Infograph: MODX Advanced Install in 7 steps:
            http://forums.modx.com/thread/96954/infograph-modx-advanced-install-in-7-steps

            Recap: Portland, OR (PDX) MODX CMS Meetup, Oct 6, 2015. US Bancorp Tower
            http://mrhaw.com/modx_portland_oregon_pdx_modx_cms_meetup_oct_2015_us_bancorp_tower
            • 27708 MODX Staff
            • 2,502 Posts
            My first simple snippet was [[copydate]]
            <?php
            $output = date(Y);
            return output;
            


            My first real snippet (that I released) was LogoutManagerLinks which generated logout/goto manager links. In hindsight it is overkill but it was an exercise that taught me a lot.

            <?php
            #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            #
            #	Snippet Name:	Logout Manager Links
            #	Written By:		Jay Gilmore (smashingred)
            #	Created:		19-12-2007
            #	Updated:		12-12-2007
            # 	Notes:			Based on Adam Crownoble's LoginLogoutLink (8/3/2005) 
            #					and QuickEdit. 
            #	Description:	Generates "Logout" and "Go to Manager" Links.
            #	Version:		0.2
            #
            #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            #	Changes
            #
            #	Version: 0.2 - 07-01-2008
            #	-added ability to use a chunk to customise output with placeholders.
            #
            #
            #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            #	Usage
            #	
            #	Simple (No Params/Default)
            #
            #	[!LogoutManagerLinks!]
            #
            #	With optional user template
            #	
            #	[!LogoutManagerLinks? &tpl=`chunkname`!]
            #
            #	Where chunkname is the name of your chunk that contains a template
            #	with the required placeholders [+loURL+] and [+mgrURL+]
            #
            #	1. Create a chunk called "lmlTml" (or whatever you want) and place your link template as below:
            #		<a href="[+loURL+]" title="Logout Link Title">Logout Now!</a><br/>
            #		<a href="[+$mgrURL+]" title="Go to Manager Title">Go to Manager Now!</a>
            #	2. Place your call in your page as below:
            #		[!LogoutManagerLinks? &tpl=`lmlTpl`!] (or using whatever you named the chunk)
            #
            #	Important!: Do not place the chunk call in the document as it will be visible to all users.
            #
            #
            #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            #	Parameters
            #		
            #	&lo_link_name - Link text to appear on page. (String)[Optional] Default: Logout
            #	&lo_link_title - Link title for the link to appear in <a> element as title value.(String)[Optional] Default: Click here to logout.
            #	&lo_doc_id - Document to send user to on logout.(String)[Optional] Default: current document.
            #	&mgr_link_name - Link text to appear on page.(String)[Optional] Default: Go to Manager.
            #	&mgr_link_title - Link title for the link to appear in <a> element as title value.(String)[Optional] Default: Click here to go to manager.
            #	&tpl - Name of chunk to use for ouput. (String)[Optional]
            #		
            #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            #	TODO
            #	- Clean Code
            #	- Add ability to use chunk id, @code:, @file:
            #
            
            
            // Link Titles and Names
            
            # Logout Link Name
            $lo_link_name = isset($lo_link_name) ? $lo_link_name : 'Logout';
            
            #Logout Link Title
            $lo_link_title = isset($lo_link_title) ? $lo_link_title : 'Click here to logout';
            
            # Manager Link Name
            $mgr_link_name = isset($mgr_link_name) ? $mgr_link_name : 'Go to Manager';
            
            # Manager Link Title
            $mgr_link_title = isset($mgr_link_title) ? $mgr_link_title :'Click here to go to the manager';
            
            # Document to go to on logout
            $lo_doc_id = isset($lo_doc_id) ? $lo_doc_id : $modx->documentIdentifier;
            
            # Generates Logout URL
            $loURL= "index.php?id={$lo_doc_id}&LML_logout=logout";
            
            # User template chunk to output 
            $tpl = isset($tpl) ? $tpl : ''; 
            
            #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            # Checks to see if the optional template chunk exists and outputs it
            $userTpl = $modx->getChunk($tpl);
            	
            
            
            # Generates Manager URL
            $mgrURL = $modx->getManagerPath();
            $lml_logout= (isset($_GET['LML_logout'])? $_GET['LML_logout']: '');
            
            #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            # Default Template to be used if no user template exists.
            
            $defaultTpl = <<<EOD
            <a href="{$loURL}" title="$lo_link_title">$lo_link_name</a> | <a href="{$mgrURL}" title="$mgr_link_title">$mgr_link_name</a>
            EOD;
            
            #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            # Placeholders Stuff
            		$pholders = array('[+loURL+]','[+mgrURL+]');
            		$swap = array("$loURL", "$mgrURL");
            		$tplOutput = str_replace($pholders, $swap, $userTpl);
            		
            #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
            # The Logic
            
            //Checks to see if user is logged in as manager.
            if($_SESSION['mgrValidated']){
            	
            	//Checks to see if the logout link has been clicked
                if($lml_logout == 'logout') {
                	//If logout link clicked is true then clear the Manager session and end the snippet.
                 $_SESSION = array();
                 } 
                 	//If User Template exists return its contents
                 elseif ($userTpl){
                            return $tplOutput;
                    }
                 else
                 {
                 	//Otherwise return the default template
                 return $defaultTpl;
                 }
             } 
             else 
            {
             	//End the script
            	return false;
            }
            
            ?>
            
              Author of zero books. Formerly of many strange things. Pairs well with meats. Conversations are magical experiences. He's dangerous around code but a markup magician. Blog ✦ Twitter ✦ LinkedIn ✦ GitHub
              • 4971
              • 964 Posts
              Jay,

              copyDate never worked because you did not close the ?> tongue

                Website: www.mercologia.com
                MODX Revo Tutorials:  www.modxperience.com

                MODX Professional Partner
                • 26931
                • 2,314 Posts
                Hi everybody,

                i’m looking at php code for quite a while now, but the initial "hooray - i got it" effect was missing so far...yesterday i jumped in and started writing my first little PHX modifier
                -> http://modxcms.com/forums/index.php/topic,40251.msg255963.html#msg255963

                ...later on that day, i finally managed to write my own (some parts are borrowed from prevjumpnext) snippet "prevtv" inspired by the following question from the "prevjumpnext" snippet forums thread ( i actually thought about that question for quite a while because i knew it would be good exercise )
                -> http://modxcms.com/forums/index.php/topic,5925.msg249233.html#msg249233

                so here it is smiley sorry for the probably dirty & bad code - ItsMyFirstSnippet and still a "work in progress". It will return the value of an (e.g. image)TV from the previous and/or next ressource:

                <?php
                /**
                 
                 * **************************
                 * Snippet: prevtv V.1.0
                 * By: sharkbait / @kunane
                 * Date: Nov 2009
                 * inspired & borrowed some parts of: PrevJumpNextXHTML Snippet
                 * from the version modified by PMS
                 * **************************
                 
                installation:
                1. create a new snippet "prevtv" and copy this code into the  Snippet code-field
                2 in your template call the snippet like this: [!prevtv? &direction=`1` &tvname=`yourtvname` !]
                
                &direction=`1` will return the value of the TV from the previous ressource
                &direction=`2` will return the value of the TV from the next ressource
                
                enter the name of the TV you want to retrieve the value
                &tvname=`yourtvname`
                
                enter the text you want to be displayed if there's no image (ressource prev. to the first / next to the last) - leave it empty if you want no text to be displayed
                &text=`no image`
                
                currently a text will be displayed "no image available" for the previous ressource of the first item and for
                the next ressource of the last item. If you don't want do display a value, just delete the string in line 72 & 89
                
                the order of the TVs  currently reflects the defauld order of Wayfinder
                 
                 sorry for the ugly code - #itsmyfirstsnippet :)
                
                */
                
                // default Wayfinder
                if(!isset($sortBy)){
                		$sortBy = 'menuindex'; 
                	}
                // default Wayfinder
                if(!isset($sortHow)){
                		$sortHow = 'ASC';
                	}
                
                // Get the value of the TV named in the Snippet call
                $pntv = $tvname;
                
                // Get the value of 
                $pntext = $text;
                
                // Get the parent ID
                $parentid = $modx->documentObject['parent'];
                
                // (re)set the $id variable to the one of this document.
                $id = $modx->documentIdentifier;
                
                // select the other members in this folder
                $children = $modx->getActiveChildren($parentid, $sortBy, $sortHow);
                
                // the number of selected documents
                $limit = count($children);
                
                // set $y to zero
                $y = 1;
                
                // sorting the documents, giving them a sequential and searchable index
                foreach ($children as $child)
                	{
                		$my_array[$y] = $child;
                		if ($my_array[$y]['id']==$id){
                		$current=$y; // The current page has number $y in the array
                		}
                		$y++;
                	}
                
                $prev = $current-1;
                $next = $current+1;
                
                // if &direction is set to 1 do this
                if ($direction == 1) {
                
                		if ($prev == 0) {
                			// in case a value previous to the first document
                			return $pntext;
                			} else {
                			// get the id of the previous document
                			$previd = $my_array[$prev]['id'];
                			// return the output of the TV  named in the Snippet call -> tvname ($pntv)
                			$document_tvs = $modx->getTemplateVarOutput(true, $previd);
                			$templatevar_output = $document_tvs[$pntv];
                			$output = $templatevar_output;
                			return $output;
                			}
                		} 
                
                // if &direction is set to 2 do this
                elseif ($direction == 2) {
                
                		if ($current == $limit) {
                			// in case a value next to the last document
                			return $pntext;
                			} else {
                			// get the id of the next document
                			$nextid = $my_array[$next]['id'];
                			// return the output of the TV  named in the Snippet call -> tvname ($pntv)
                			$document_tvs = $modx->getTemplateVarOutput(true, $nextid);
                			$templatevar_output = $document_tvs[$pntv];
                			$output = $templatevar_output;
                			return $output;
                			}
                		}
                		else {
                		$output = '';
                		return $output;
                		}
                ?>

                ...hope it will be useful to someone

                demopage: www.kunane.com/modx/prevtv-01.html

                p.s. before that, i once "wrote" a tinytiny plugin: http://modxcms.com/forums/index.php/topic,37248.0.html - but that doesn’t count
                  • 27708 MODX Staff
                  • 2,502 Posts
                  Charliez,

                  It may not work in MODx but it should. Closing ?> is not required nor is the last ;

                    Author of zero books. Formerly of many strange things. Pairs well with meats. Conversations are magical experiences. He's dangerous around code but a markup magician. Blog ✦ Twitter ✦ LinkedIn ✦ GitHub
                    • 4858
                    • 3 Posts
                    This is my first one, allowing you to include one ore more stylesheets to a document (snippet call to be placed in the head section of your template).
                    I used the same concept to create a customJS snippet.

                    <?php
                    /*
                    Snippet name: customCSS
                    Description: Add one or more CSS file to a page.
                    Dependency: customCSS TV
                    Parameters: basePath, cssPath (includes path and filename with extension)
                    Template ex: [[customCSS? &basePath=`[(base_url)]`&cssPath=`[*customCSS*]`]]
                    */
                    
                    if (isset($basePath) && isset($cssPath) && $cssPath!='' && $cssPath!='/') {
                    	$arCssPath = split(':',$cssPath);
                    	foreach ($arCssPath as &$thisCssPath) {
                    		$cssFilePath = $basePath.$thisCssPath;
                    		echo('<link type="text/css" href="'.$cssFilePath.'" rel="stylesheet" />'."\n");
                    	}
                    }
                    ?>


                    The fields for the associated TV
                    Variable Name: [*customCSS*]  
                    Caption: Custom CSS file
                    Description: CSS file paths (delimit with : , prevent inheriting with /)
                    Input Type: Text
                    Default Value: @INHERIT
                      • 9994
                      • 133 Posts
                      Nice! I will try this out. It’s what i needed laugh
                        Best CMS eva!