Search code examples
phpvariablescode-snippetsmodxmodx-revolution

ModX: 2 snippets on same page interacting with each other


I have 2 snippets (below). The issue is the if statemnt if ($loggedin != NULL){ in the 2nd snippet doesnt pass even if the variable is not null. Its like the $loggedin variable in the 1st snippet doesnt apply to it. If I combine the 2 snippets into 1 they work fine.

Does anyone know how to make 2 snippets 'talk' to each other? (ps, running Revo 2.1.3)

<?php
$loggedin = "";
if (!isset($_SESSION['user_id'])) {
 // redirect to login page
}
else {
$loggedin = "true";
}

2nd:

<?php
if ($loggedin != NULL){
echo  "logged in";
}
else {
echo  "error";
}

Solution

  • First off, you are not passing the $loggedin variable to the second snippet, do this normally with a post or session variable.

    Second, there is an easier way to check, these are straight out of Bob's guides.:

    There are various methods. One easy method is to use this code:
    
    if ($modx->user->get('username') == '(anonymous)') {
        /* user is not logged in */
    }    
    Here is the official method for seeing if the user is logged in 
    to the current context:
    
    if ($modx->user->hasSessionContext($modx->context->get('key'))) {
        /* user is logged in */
    }    
    If you know the name of the current context (e.g., web), 
    you can use this method. The name of the context is required:
    
    if $modx->user->isAuthenticated('web') {
        /* user is logged in to web context */
    }  
    

    that is if you need to roll your own authentication for some reason. ~ Otherwise, the login/register extra will do all of this for you.

    *UPDATE*** Two pass variables from one snippet to another in the same resource you can set/get placeholders:

    <?php
    // snippet one
    
    $modx->setPlaceholder('output','Place holder set!');
    
    
    
    <?php
    // snippet two
    
    $myvar = $modx->getPlaceholder('output');
    
    echo 'this is the value of "output": '.$myvar;