We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 19975
    • 429 Posts
    SandersDesign Reply #1, 16 years ago
    I would like to set a PHP Cookie value with via an ’a href’ link, I have scripted the following using code with the $_GET[] but this seems to have a delay, meaning that a refresh is manual browser is required to view the cookie value.

    <?php
    if($_GET['lang'] == 'ker') {
        setcookie ("lang", "ker");	
    } elseif ($_GET['lang'] == 'eng') {
        setcookie ("lang", "eng");	
    };
    ?>


    Any help or suggestions very welcome.

    Many thanks,

      Martin Sanders - Design & Web Development
      • 33372
      • 1,611 Posts
      AFAIK, cookie values are not available until the next time you load a page, so that would explain the "delay" that you’re seeing. But you can always just change your language selection logic to use either the cookie value or $_GET[’lang’] (if that’s set). Then it should work on the first and subsequent page loads.
        "Things are not what they appear to be; nor are they otherwise." - Buddha

        "Well, gee, Buddha - that wasn&#39;t very helpful..." - ZAP

        Useful MODx links: documentation | wiki | forum guidelines | bugs & requests | info you should include with your post | commercial support options
        • 19975
        • 429 Posts
        SandersDesign Reply #3, 16 years ago
        Hi ZAP,

        Thanks for the reply, to add a little more detail I have two links:
        <a href="?lang=ker">Kernewek</a><a href="?lang=eng">English</a>


        So that when clicked the pages are refreshed. I have also scripted the following PHP Snippet to filter which TV to show based on the $_GET value:


        <?php
        /* Example snippet	: [!langGet? &outputKer=`[*pagetitle*]` &outputEng=`[*description*]` &link=`1` !]
         * &outputKer 		: output for Cornish language
         * &outputEng 		: output for English language
         * &output			: output used for default
         * &link			: use value of 1 to include ?lang= url parameter
         */
        
        if($_GET['lang'] == 'ker' || $_COOKIE['lang'] == 'ker') {
                echo $outputKer;
                if($link == 1){
                    echo "?lang=ker";
                };
           
        } elseif ($_GET['lang'] == 'eng' || $_COOKIE['lang'] == 'eng') {
                echo $outputEng;
                if($link == 1){
                    echo "?lang=eng";
                };
        
        } else {
            if(isset($output)){
                echo $output;
            } else {
        		echo $outputEng;
                if($link == 1){
                    echo "?lang=eng";
                };
            };
        };
        ?>
        


        While the above code works well if the parameter lang has a value within the URL I had hoped that adding a cookie would add a extra layer of selection to ensure that the user remains in the correct language view.

        Can the above code be improved? Thanks.
          Martin Sanders - Design & Web Development
          • 33372
          • 1,611 Posts
          What you’re doing looks fine to me, and yes I would also think that you’d want to set a cookie so that pages loaded after that first one with the language variable in the query string will continue to show the selected language. It’s hard to tell from your code fragment what exactly you’re outputting (and the code to set the cookie isn’t in there). Are you saying that it doesn’t work the way that you expect it to?

          The only thing that I would probably do differently is more a personal preference than anything else. I would set a $language variable at the beginning of my code (probably where you set the cookie) which checks $_GET[’lang’] and $_COOKIE[’lang’] and uses the query string value if it’s provided and the cookie value if not (and sets a default value if neither exists). That way in your later logic you don’t have to check the values of both $_GET[’lang’] and $_COOKIE[’lang’] in every if statement (you could probably just use a more concise switch statement instead).

          If you’re needing to use the language value over several snippets or plugins, try setting a session var at the beginning, since that will be available in all of those contexts.
            "Things are not what they appear to be; nor are they otherwise." - Buddha

            "Well, gee, Buddha - that wasn&#39;t very helpful..." - ZAP

            Useful MODx links: documentation | wiki | forum guidelines | bugs & requests | info you should include with your post | commercial support options
            • 19975
            • 429 Posts
            SandersDesign Reply #5, 16 years ago
            Thanks for the in-depth feedback, could you show me how it would look, I’m still learning PHP wink
              Martin Sanders - Design & Web Development
              • 33372
              • 1,611 Posts
              If your code is working then there’s no need to change it. The suggestions I made were just personal style. People write code very differently, and you should do whatever works well for you.

              You could assign a $language (or $_SESSION[’language’]) var at the beginning like so:
              $language=(isset($_GET['lang'])) ? $_GET['lang'] : (isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'eng');

              Some people hate ternary operators - and especially nested ones like this - because they’re more difficult to read and debug. This is just the equivalent of if..elseif...else, but it’s a lot shorter. If you wanted to do something else other than assign the value of $language in one or more of these conditions (for example, set the cookie if there’s a GET value), then if statements would definitely be better.

              A switch statement might make your $output generation more readable, and it’s generally better to write MODx snippets to return one output at the end rather than echoing throughout. I’m assuming that you’re writing a snippet here, anyway. In order to have a single exit point and return one output var, I’d probably do something like this:
              $output='';
              
              ...
              other code in here... setting the language var, cookies, whatever...
              ...
              
              switch ($language){
                 case 'ker':
                    $output=$outputKer;
                    break;
                 case 'eng':
                    $output=$outputEng;
                    break;
                  default:
                    $output=$outputEng;
              }
              
              return $output;
              


              You could set link placeholders or whatever else you need within this also. As you can see, the English case may be redundant if that’s your default, so you could just eliminate that. Using a switch statement is more of a preference than a best practice, but you should definitely return just one value from each snippet rather than echoing throughout them.
                "Things are not what they appear to be; nor are they otherwise." - Buddha

                "Well, gee, Buddha - that wasn&#39;t very helpful..." - ZAP

                Useful MODx links: documentation | wiki | forum guidelines | bugs & requests | info you should include with your post | commercial support options
                • 19975
                • 429 Posts
                SandersDesign Reply #7, 16 years ago
                Hi Zap,

                I’ve managed to script the following snippet which seems almost to almost work, my only issue is when I adding class="" tags within the parameters the script stops. How would I enable HTML within the snippet.


                <?php
                /* Example snippet	: [!langGet? &outputKer=`[*pagetitle*]` &outputEng=`[*description*]` &link=`1` !]
                 * &outputKer 		: output for Cornish language
                 * &outputEng 		: output for english language
                 * &link			: use value of 1 to include ?lang= url parameter
                 */
                 
                $language = (isset($_GET['lang'])) ? $_GET['lang'] : (isset($_COOKIE['lang']) ? $_COOKIE['lang'] : 'eng');
                $output='';
                
                switch ($language){
                	case 'ker':
                			if($link == 1){
                				$link = "?lang=ker";
                			};
                		$output=$outputKer . $link;
                		setcookie ('lang', 'ker');
                		break;
                	case 'eng':
                			if($link == 1){
                				$link = "?lang=eng";
                			};
                		$output=$outputEng . $link;
                		setcookie ('lang', 'eng');
                		break;
                	default:
                		if(isset($outputBilingual)){
                			$output=$outputBilingual;
                		} else {
                			if($_COOKIE['lang'] == "ker"){
                				$output=$outputKer;
                			} elseif ($_COOKIE['lang'] == "eng"){
                				$output=$outputEng;
                			} else {
                				$output=$outputEng;
                		};
                	};
                };
                return $output;
                ?>
                


                  Martin Sanders - Design & Web Development
                  • 33372
                  • 1,611 Posts
                  If I understand you correctly, you’re saying that you’re passing HTML in your snippet parameters and that’s breaking the script? If so, then yes that will very likely break things and you probably shouldn’t do it. A lot of characters can break snippet parameters (including ? and &), so you should probably create chunks and pass chunk names in your parameters (or something like that).
                    "Things are not what they appear to be; nor are they otherwise." - Buddha

                    "Well, gee, Buddha - that wasn&#39;t very helpful..." - ZAP

                    Useful MODx links: documentation | wiki | forum guidelines | bugs & requests | info you should include with your post | commercial support options
                    • 28042 ☆ A M B ☆
                    • 24,524 Posts
                    ? & and = can’t be used in snippet parameters. There are a number of ways to get around this; my preference is to code my snippet to accept an external config file and specify the config file name in the snippet’s parameter. That way the config file name is the only parameter you need. The config file just takes ordinary PHP variable declarations; $param1 = ’value1’; $param2 = ’value2’; etc.

                    Another common way is to use something like |q|, |a| and |e| in the parameter, then use str_replace to convert them to ?, & and = in your snippet code.

                    Yet another way is to use a wrapper snippet, with $modx->runSnippet(’mySnippet’, array(’param1’=>’value1’, ’param2’=>’value2’, ... ); so in the array you can put whatever you want.
                      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
                      • 19975
                      • 429 Posts
                      SandersDesign Reply #10, 16 years ago
                      I’ve been using chunks to include my code, however if there are any illegal characters within the code the snippet stops working.

                      Example chunk:
                      <div class=""></div>
                        Martin Sanders - Design & Web Development