We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 27708 MODX Staff
    • 2,502 Posts
    I am trying to refactor a stylesheet switcher but I am running into problems. I have created a snippet to include the logic code and I have made adjustments to the logic code to return a value from functions but I am not sure how to get what I want out of it or if it is even possible with a snippet.

    The snippet code is here:
    <?php
    global $modx;
    require_once($modx->config['base_path'] .'assets/snippets/srmSwitch/srmSwitch.inc.php');
    $ulSwitch = mSwitch('ul');
    $modx->setPlaceholder('ul_switch', '$ulSwitch');
    ?>

    The include code is here:
    <?php
    
    //////////////////////////////////////////////////////////////////////////////
    // minimal Switch 1.0.1 is © 2005 minimal design							//
    // but feel free to use and abuse it as much as you want					//
    // just don't sell it or say you made it - that's all						//
    // for info/feedback/requests/help/donations ;) go to						//
    // http://minimaldesign.net/												//
    //////////////////////////////////////////////////////////////////////////////
    
    // EDIT if you don't put style sheets in default location
    global $modx;
    $style_dir = $modx->config['base_path']. 'assets/templates/modxhost/';
    
    
    // DON'T EDIT AFTER THIS LINE (unless you know what you're doing I guess ;)
    
    $t = $_GET['t']; // in case register_globals in php.ini is Off
    $script_name = eregi_replace("[^[:alnum:]+]"," ",basename($_SERVER['PHP_SELF'], ".php"));
    $here = basename($_SERVER['PHP_SELF']);
    $path2switcher = dirname($_SERVER['PHP_SELF']);
    $site_uri = 'http://'.$_SERVER['SERVER_NAME'];
    
    // scans $style_dir for themes and populates $styles
    if ($dh03 = opendir($style_dir)) {
    	while (($style = readdir($dh03)) !== false) {
    		if($style != "." && $style != ".." && $style != ".DS_Store" && is_file("$style_dir$style")) {
    			$styles[] = eregi_replace(".css","",$style);
    		}
    	}
    }
    closedir($dh03);
    
    // clean up and arrange $styles array
    $total_styles = count($styles);
    natcasesort($styles);
    $styles_sorted = array_slice($styles, 0, $total_styles);
    for ($i=0; $i<$total_styles; $i++) {
    	$styles_name[$i] = eregi_replace("[^[:alnum:]+]"," ",$styles_sorted[$i]);
    }
    
    // sets cookie to remember style between visits if $theme = 'multi'
    if (!isset($_COOKIE['current_style'])) {										// if cookie ain't set
    	setcookie('current_style', $styles[0], time()+2592000, $path2switcher);
    	$current_style = $styles[0];
    	} else if (isset($t)) {														// if cookie set and switching
    	setcookie('current_style', $t, time()+2592000, $path2switcher);
    	$current_style = $t;
    	} else if (!isset($t)) {													// if cookie set and ain't switching
    	$current_style = $_COOKIE[current_style];
    }
    
    // style switcher function that goes on index.php
    // 3 possible options 'ul' for unordered list (default), 'ol' for ordered list, and 'select' for a drop down menu
    function mSwitch($type='ul') {
    	global $here, $current_style, $total_styles, $styles_sorted, $styles_name;
    	if ($type == 'ul' || $type == 'ol') {
    		$output = "<$type>";
    		for ($i=0; $i<$total_styles; $i++) {
    		$output .= "<li><a href=\"$here?t=$styles_sorted[$i]\" title=\"switch to $styles_name[$i] CSS style\"".($styles_sorted[$i] == $current_style ? ' class="selected"':'').">$styles_name[$i]</a></li>";
    		}
    		$output .= "</$type>";
    		
    	} else if($type == 'select') {	
    		$output = '<form action=""><p>
    			<select name="select_style" onchange="window.location=(this.form.select_style[this.form.select_style.selectedIndex].value);">
    			<option value="">select a style</option>';
    			for ($i=0; $i<$total_styles; $i++) {
    		$output .=	"<option value=\"$here?t=$styles_sorted[$i]\"".($styles_sorted[$i] == $current_style ? ' selected="selected"':'').">$styles_name[$i]</option>";
    			}
    		$output .= '</select></p></form>';
    	}
    	print $output;
    }
    
    // 'cause it's always nice to show it's Standard compliant ;)
    function validation() {
    	echo("valid <a href=\"http://validator.w3.org/check/referer\" title=\"valid XHTML 1.0 strict\">xhtml</a> | <a href=\"http://jigsaw.w3.org/css-validator/check/referer\" title=\"valid CSS 2.0\">css</a>");
    }
    ?>


    What I’d like to achieve is the ability to call the snippet in the template header and have the selector links show in the page (via placeholder or other snippet call and have the dynamic css file name in the head either via placeholder or third snippet.

    First I am no PHP programmer. I am a guy who knows some PHP (dangerous, I know).

    I wonder if it makes sense to lose the function and just call the $output but as another variable name for the various outputs or using a parameter.

    Any thoughts or direction would be good.

    I do know that there is a cssSwitcher but it is designed for switching between print and screen. This is to use a high contrast stylesheet for users with visual impairment or screen preference for WAI (a client).

    Cheers,

    Jay

    PS: Don’t be afraid to tell me I’m doing it all wrong smiley
      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
      • 27708 MODX Staff
      • 2,502 Posts
      Okay so no takers oh well. I ended up writing a new switcher from the ground up using $modx->regClientCSS(); which works like a charm for this and only requires a single call in the templates. I will release it as soon as I finish making the code clean and externalizing the parameters and templating elements.

      Cheers,

      Jay

      PS: I know there is a cssSwitcher in the repository but it was too much for my needs and was desiged to switch between screen and print versions. Mine is designed to enable alternate/accessible styles.
        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
        • 6726
        • 7,075 Posts
        No takers ?
        Don’t be so sure !

        I am planning to build a template subdomain for modxcms.fr as a showcase of MODx flexible templating (and have us frenchies produce some templates) and I sure would be interrested...

        And the idea of using this for print/alternate styles : I like it better than using js smiley
          .: COO - Commerce Guys - Community Driven Innovation :.


          MODx est l&#39;outil id
          • 5811
          • 1,717 Posts
          HI Smashingred & David

          To develop the AjaxSearch Demo Site, I have used of lots of some stuff switchers (docswitcher, langswitcher and cssSwitcher). All these switchers are all based on 3 re-usable simple classes:

          - switcher class, to switch any string between two pages
          - select class, to build a select drop down menu (with or without submit button)
          - htmllist class, to build a html list (with or without background image)

          This version of cssSwitcher adds more flexible templating usages based on the chunckie class and a correction to the redeclare getchunck error of 0.4 version.
          See http://modxcms.com/forums/index.php/topic,3597.msg139544.html#msg139544

          Still now I awaited an answer from Guillaume (the owner of CssSwitcher) before updated the repository with this new version, but I think that at the end I will deliver these pratical snippets in the repository.

          Smashingred, these three classes could be usefull if you want set up a simple cssSwitcher (without print option for example).

          Let me know if you want more information about these stuff Switchers

          An another possibility to change the css style sheet is also to use ajax ... A future release in perspective wink

          You could see the docSwitcher and the cssSwitcher work on AjaxSearch Demo Site
            • 27708 MODX Staff
            • 2,502 Posts
            coroico,

            I don’t know if it was my setup but I could not get your version of the script (the one on the cssSwitcher) thread to work. Granted, I was working on a test site on a remote server but it felt like overkill for what I needed. I’ll reinstall it onto my local test install and see how it goes.

            That being said. I worked on my srCssSwitch last night and have managed to get it almost half done for someone who wants to just switch between two stylesheets regardless of the purpose.

            I like the flexibility of yours so as I said I will try it out.

            The fact of the matter is that I am really enjoying learning how to dig into the MODx APi more to take advantage of built in features for snippets. For someone who considers himself still very much a PHP beginner it helps me learn more and more skills.

            I think I will end up releasing srCssSwitch as a lean, light single purpose snippet and for those who want a more robust or flexible solution, I will recommend your "stuff" swithcher.

            Maybe you’ed be interested providing a lttle feedback on my script when it is done to see where I could tidy things. I love to learn more and just ’cause it works doesn’t make it perfect.

            Cheers and all the best.

            Jay
              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
              • 5811
              • 1,717 Posts
              @smashingred

              I don’t know if it was my setup but I could not get your version of the script (the one on the cssSwitcher) thread to work
              What are your concern about the use of ccsSwitcher ? Do not forget in the includes/snippet.cssSwitcher.inc.php file to initialise the CS_CSSPATH constant to your own css folder.

              Maybe you’ed be interested providing a lttle feedback on my script when it is done to see where I could tidy things.
              No problems, do not hesitate to post your snippet, I will give you my feedback.
                • 27708 MODX Staff
                • 2,502 Posts
                @coroico

                I will try it out on my local setup to see how it works. As I said it was on a client’s test website (private label contract work) and I didn’t try it on my local first. The other thing was that I didn’t have access to install myself and the files were accidentally installed into assets instead of assets snippets so they were a mess. It likely had more to do with it than any possible issues with the script.

                Cheers,

                Jay

                PS: I will post here when I have the snippet ready for consumption. I just want some constructive feedback as I am still with training wheels with PHP and OOP and I want to get better. -J
                  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
                  • 27708 MODX Staff
                  • 2,502 Posts
                  @coroico,

                  I have gotten to the point where I would like some quick feedback if you had time on the snippet. Once you have had a chance to check it out. I will move this over to the appropriate forum.

                  What I am looking for is to know:

                  1. What can and should be externalized (all the elements that could be in an include?)
                  2. Is there anything blatently wrong?
                  3. Any suggestions on possible corrections, pitfalls, changes, flaws?
                  4. Any thoughts on how to comment the code better?
                  5. Do you think it is worthwhile to worry about externalising the error presentation?
                  6. Since it is so small do you think that it is worth the effort to move the presentational templates out of the snippet?

                  I am planning on migrating the links out to a template and creating the placeholders for the output in a chunk so that people will be able to create their own output so I don’t need to add any other styles for the links, they can do it all themselves.

                  Cheers, and any others are allowed to offer opinions.

                  Jay
                    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
                    • 5811
                    • 1,717 Posts

                    1. What can and should be externalized (all the elements that could be in an include?)

                    Personally, I prefer limit the content of the snippet to the call to an include file. It makes easier the debuging and avoid to reload at each modification the content in MODx. To avoid to link a wrong include file you could add the version number as a constant and check this version number in the include file.

                    Otherwise, put your templates in dedicated html files. Each Php class should have its own file. Group your common functions in a same include file.
                    Externalise Js code (except if you have few initialisation of variables for instance) as an external file.
                    As much as possible try to search and limit coupling between your code elements to loose coupling. It will be easier to change later.

                    2. Is there anything blatently wrong?

                    No, you code is correct
                    3. Any suggestions on possible corrections, pitfalls, changes, flaws?
                    Nothing
                    4. Any thoughts on how to comment the code better?
                    No it ’s readeable easily (for a Php developper)
                    5. Do you think it is worthwhile to worry about externalising the error presentation?
                    No I think it’s not necessary.
                    Regarding the required values sheetOne, sheetTwo and filePath you could also initialize the values with existing values like default stylesheets from default template.

                    6. Since it is so small do you think that it is worth the effort to move the presentational templates out of the snippet?
                    If you publish your snippet, I think you could avoid many posts wink about how style the links, if they are in a default template (or a chunck thru a parameter) and shaped with placeholders. Try to limit the number of file templates. If needed use the chunckie class and PHX. Look at cssSwitcher to see how are styled the htmllist and the select elements. Maxigallery has also some very interesting templates. A good school.
                      • 27708 MODX Staff
                      • 2,502 Posts
                      Thanks coroico,

                      I have read your comments--they all make perfect sense--I’ll use them to revise the snippet for release. I have one part I don’t fully understand though. You mentioned the following:
                      Quote from: coroico at Mar 11, 2008, 07:45 PM

                      As much as possible try to search and limit coupling between your code elements to loose coupling. It will be easier to change later.

                      I am not 100% sure what you are saying here. Is there some reference I could read about coupling? Or could you explain it? I am entirely self taught to so anywhere I can learn terms or syntax descriptions I will.

                      Thanks again for your help.

                      Jay
                        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