Custom PHP - Chunks, Snippets, pdoTools

I’ve been working on adding Chunks, Snippets, pdoTools that I created in MODX to a custom PHP page. I’m able to add the chunk with the code below no problem but what happens if a chunk has a snippet or pdoResources or pdoMenu inside it? How do you add them then also? I tried parsing but no joy

This works for the Chunks

<?php
  // Define the MODX_CORE_PATH if it's not already defined
  if (!defined('MODX_CORE_PATH')) {
      define('MODX_CORE_PATH', 'C:/wamp64/www/sitename/core/');
  }
  
  // Include MODX config
  require_once MODX_CORE_PATH . 'config/config.inc.php';
  
  // Initialize MODX
  $modx = new modX();
  $modx->initialize('web');
  
  // Check if MODX initialization was successful
  if (!$modx) {
      die('MODX initialization failed!');
  }
  
  // Define the chunk name
  $chunkName = 'footer';
  
  // Get the chunk object
  $chunk = $modx->getObject('modChunk', array('name' => $chunkName));
  
  // Check if the chunk exists
  if ($chunk) {
      echo $chunk->getContent();
  } else {
      echo 'Chunk not found.';
  }
?>

There is a pdoResources, pdoMeno and a snippet within the chunk

I’m not sure if this helps - but you can run snippets direct [and uncached] from your PHP code like this:

$pdoMenuOutput = $modx->runSnippet('pdoMenu',array(
   'parents'  => '0',
   'depth'    => '0',
   'tpl'      => 'navTpl-Footer'
));
echo $pdoMenuOutput ;

PS - I could be wrong but I think when you call your chunk:

$chunk->getContent();

… the results of any snippets within that chunk should be returned in the content.

Did that not happen?

If you look at the image I attached, it show’s how the pdoResourses, pdoMenu and the snippet in the chunk is displayed. It comes up as text.

The pdoMenu comes up like this

[[!pdoMenu? &parents=`0` &depth=`0` &tpl=`navTpl-Footer` ]]

This does work but I’ll have to hard code my initial chunk and then add the pdoMenu, pdoResoures and the snippet

Of course! Apologies I hadn’t put two and two together there!

I’ve tested this setup [snippet within the chunk] and it seemed to render the output as expected for me - so not sure what’s different. Others might have more insight / better suggestions!

I tried cached and uncached to see…no change :frowning:

This code outputs the content of a chunk, but does not parse the content.

You could use the function $modx->getChunk($chunkName, $properties) instead, that runs the parser, or maybe use $chunk->process($properties).

Apologies HTH…I tried a few things here but getting errors.

// Initialize MODX
$modx = new modX();
$modx->initialize('web');

// Check if MODX initialization was successful
if (!$modx) {
    die('MODX initialization failed!');
}

// Define the chunk name
$chunkName = 'footer';

// Get the parsed content of the chunk
$chunk = $modx->getChunk($chunkName, $properties);

// Output the parsed content
echo $chunk;

What errors?

Also, as you are loading MODX externally, some variables (like e.g. $modx->resource) are not set, but the snippets in your chunk may try to access it.
Is there a reason why you are loading MODX externally?

I have a website that I’m close to finishing. On the website I have a a simple add-to-cart button that adds items to a shopping cart and then the basket page has a clear, delete and update buttons. There is also a pay with PayPal button. I had this code working first on .php pages.

  1. shop.php
  2. basket.php

When I added the item to the cart, I can see it in the shopping cart on the shop.php page and when I went to basket.php, I also see it.

But when I tried to so it in chunks and snippets on Modx, I’m able to add the items to the cart and basket, but I don’t see them in the shopping cart instantly. I need to refresh the page first to see the changes. I’ve tried AJAX but my JavaScript is very limited. Actually my PHP is too…I’m learning

This is my shop.php page. You’ll see php code at the top and also around the shopping cart displaying the items added. You’ll see the html button also.

<?php
  // Error checker
  error_reporting(E_ALL);
  ini_set("display_errors", 1);
  
  // Start or resume the session
  session_start();
  
  // Check if the cart array is not initialized in the session, initialize it
  if (!isset($_SESSION["cart"])) {
    $_SESSION["cart"] = [];   
  }
  
  // Check if the request is to add an item to the cart
  if (isset($_POST["add_to_cart"])) {
    // Validate and sanitize input
    $product_id = filter_input(INPUT_POST, "product_id", FILTER_SANITIZE_NUMBER_INT);
    $quantity = filter_input(INPUT_POST, "quantity", FILTER_VALIDATE_INT, array("options" => array("min_range" => 1)));
    
    if ($product_id !== false && $quantity !== false) {
      // Check if the product is already in the cart
      if (isset($_SESSION["cart"][$product_id])) {
        // If it is, increment the quantity by the selected multiplier
        $_SESSION["cart"][$product_id]["quantity"] += $quantity;
      } 
      else {
        // If it's not, add it to the cart with the selected quantity
        $_SESSION["cart"][$product_id] = array(
          "quantity" => $quantity,
          "product_name" => "Product " . $product_id,
          "product_price" => 250.00,
        );
      }
    } 
    else {
      // Handle invalid input (e.g., display an error message)
      echo "Invalid input. Please check your input values.";
    }
  }
?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
  <head>
    <!-- head code here -->
  </head> 

  <body class="stretched">
      <header id="header" class="header-size-sm" data-sticky-shrink="false">
        <!-- some header code here -->
                
        <!-- Top Cart
        ============================================= -->
        <?php foreach ($_SESSION["cart"] as $product_id => $product): ?>
          <?php
            $quantity = $product["quantity"];
            $discount = ($quantity == 1) ? 0 : ($quantity == 2 ? 0.10 : 0.20);
            $fullPrice = $product["quantity"] * $product["product_price"];
            $discountAmount = $fullPrice * $discount;
            $discountedPrice = $fullPrice - $discountAmount;
          ?>
          <div id="top-cart" class="header-misc-icon d-none d-sm-block">
            <a href="#" id="top-cart-trigger"><i class="uil uil-shopping-bag"></i><span class="top-cart-number"><?= $quantity; ?></span></a>
            <div class="top-cart-content">
              <div class="top-cart-title">
                <h4>Shopping Cart</h4>
              </div>
              <div class="top-cart-items">
                <div class="top-cart-item">
                  <div class="top-cart-item-image">
                    <a href="#"><img src="http://localhost/cpnag.ie/assets/images/shop/1.jpg" alt="Ad"></a>
                  </div>
                  <div class="top-cart-item-desc">
                    <div class="top-cart-item-desc-title">
                      <a href="#"><?= htmlspecialchars($product["product_name"]); ?></a>
                      <span class="top-cart-item-price d-block">&euro;<?= number_format($fullPrice, 2); ?></span>
                    </div>
                    <div class="top-cart-item-quantity">x <?= $quantity; ?></div>
                  </div>
                </div>
              </div>
              <div class="top-cart-action">
              <span class="top-checkout-price">&euro;<?= number_format($discountedPrice, 2); ?></span>
              <a href="basket.php" class="button button-3d button-small m-0">Cart</a>
              </div>
            </div>
          </div>
        <?php endforeach; ?>                
      </header>

      <!-- Content
      ============================================= -->
      <section id="content">
        <div class="content-wrap">
          <div class="container clearfix">
            <div class="row">
            
              <div class="single-product">
                <div class="product">
                  <div class="row gutter-40">
                    <div class="col-md-12 product-desc">
                      <div class="d-flex align-items-center justify-content-between">
                        <div class="product-price"><ins>&euro;250.00</ins></div>
                        <?php if (!empty($_SESSION['cart'])): ?>
                          <form class="cart mb-0 d-flex justify-content-between align-items-center" action="basket.php" method="get">
                            <button type="submit" class="add-to-cart button m-0">View Cart</button>
                          </form>
                        <?php endif; ?>
                      </div>
                      
                      <div class="line"></div>
                                            
                      <form class="cart mb-0 d-flex justify-content-between align-items-center" method="post">
                        <div class="quantity">
                          <input type="button" value="-" class="minus">
                          <input type="number" step="1" min="1" name="quantity" id="quantity" value="1" title="Qty" class="qty">
                          <input type="button" value="+" class="plus">
                        </div>
                        <button type="submit" name="add_to_cart" class="add-to-cart button m-0">Add to Cart</button>
                      </form>
                    </div>
                    <div class="w-100"></div>                   
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    
    <!-- JavaScripts
    ============================================= -->
    <script src="assets/js/plugins.min.js"></script>
    <script src="assets/js/functions.bundle.js"></script>
  </body>
</html>

And this is my basket.phph code.

<?php
  // view_cart.php
  
  // Error checker
  error_reporting(E_ALL);
  ini_set("display_errors", 1);
  
  // Start or resume the session
  session_start();
  
  // Check if the cart array is not initialized in the session, initialize it
  if (!isset($_SESSION["cart"])) {
      $_SESSION["cart"] = [];
  }
  
  // Check if the "Clear Cart" button is clicked
  if (isset($_POST["clear_cart"])) {
      // Clear the cart
      $_SESSION["cart"] = [];
  }
  
  // Check if the "Remove from Cart" button is clicked
  if (isset($_POST["remove_from_cart"]) && isset($_POST["product_id"])) {
      $productId = $_POST["product_id"];
      // Decrease quantity by one for the selected product
      if (isset($_SESSION["cart"][$productId])) {
          $_SESSION["cart"][$productId]["quantity"]--;
          // Remove the product from the cart if the quantity reaches zero
          if ($_SESSION["cart"][$productId]["quantity"] <= 0) {
              unset($_SESSION["cart"][$productId]);
          }
      }
  }
  
  // Check if the "Update Cart Quantity" button is clicked
  if (isset($_POST["update_cart_quantity"]) && isset($_POST["product_id"]) && isset($_POST["quantity"])) {
      $productId = $_POST["product_id"];
      $quantity = intval($_POST["quantity"]);
      // Update quantity for the selected product
      if (isset($_SESSION["cart"][$productId])) {
          $_SESSION["cart"][$productId]["quantity"] = $quantity;
      }
  }
?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
  <head>  
    <!-- head code here -->
  </head> 

  <body class="stretched">
      <header id="header" class="header-size-sm" data-sticky-shrink="false">
                
        <!-- Top Cart
        ============================================= -->
        <?php foreach ($_SESSION["cart"] as $product_id => $product): ?>
          <?php
            $quantity = $product["quantity"];
            $discount = ($quantity == 1) ? 0 : ($quantity == 2 ? 0.10 : 0.20);
            $fullPrice = $product["quantity"] * $product["product_price"];
            $discountAmount = $fullPrice * $discount;
            $discountedPrice = $fullPrice - $discountAmount;
          ?>
          <div id="top-cart" class="header-misc-icon d-none d-sm-block">
            <a href="#" id="top-cart-trigger"><i class="uil uil-shopping-bag"></i><span class="top-cart-number"><?= $quantity; ?></span></a>
            <div class="top-cart-content">
              <div class="top-cart-title">
                <h4>Shopping Cart</h4>
              </div>
              <div class="top-cart-items">
                <div class="top-cart-item">
                  <div class="top-cart-item-image">
                    <a href="#"><img src="http://localhost/cpnag.ie/assets/images/shop/1.jpg" alt="Ad"></a>
                  </div>
                  <div class="top-cart-item-desc">
                    <div class="top-cart-item-desc-title">
                      <a href="#"><?= htmlspecialchars($product["product_name"]); ?></a>
                      <span class="top-cart-item-price d-block">&euro;<?= number_format($fullPrice, 2); ?></span>
                    </div>
                    <div class="top-cart-item-quantity">x <?= $quantity; ?></div>
                  </div>
                </div>
              </div>
              <div class="top-cart-action">
              <span class="top-checkout-price">&euro;<?= number_format($discountedPrice, 2); ?></span>
              <a href="http://localhost/cpnag.ie/siopa/cisean.php" class="button button-3d button-small m-0">Cart</a>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      </header>

      <!-- Content
      ============================================= -->
      <section id="content">
        <div class="content-wrap">
          <div class="container clearfix">
            <div class="row">
              <!-- View Cart Table
              ============================================= -->
              <div class="col-12 pb-6">
                <?php if (!empty($_SESSION["cart"])): ?>
                  <table class="table cart mb-5">
                    <thead>
                      <tr>
                        <th class="cart-product-remove">&nbsp;</th>
                        <th class="cart-product-thumbnail">&nbsp;</th>
                        <th class="cart-product-name">Name</th>
                        <th class="cart-product-price">Price</th>
                        <th class="cart-product-quantity">Quantity</th>        
                        <th class="cart-product-fullprice">Total Cost</th>
                        <th class="cart-product-discount">Discount</th>
                        <th class="cart-product-subtotal">Discount Price</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach ($_SESSION["cart"] as $product_id => $product): ?>
                        <?php
                          $quantity = $product["quantity"];
                          $discount = ($quantity == 1) ? 0 : ($quantity == 2 ? 0.10 : 0.20);
                          $fullPrice = $product["quantity"] * $product["product_price"];
                          $discountAmount = $fullPrice * $discount;
                          $discountedPrice = $fullPrice - $discountAmount;
                        ?>
                        <tr class="cart_item">
                          <td class="cart-product-remove">
                            <form action="" method="post" class="mb-0">
                              <input type="hidden" name="remove_from_cart" value="1">
                              <input type="hidden" name="product_id" value="">
                              <button type="submit" class="button button-mini button-circle button-border button-red remove-from-cart"><i class="fa-solid fa-trash me-0"></i></button>
                            </form>
                          </td>
                          <td class="cart-product-thumbnail"><img width="64" height="64" src="http://localhost/cpnag.ie/assets/images/shop/1.jpg" alt=""></td>
                          <td class="cart-product-name"><?= htmlspecialchars($product["product_name"]); ?></td>
                          <td class="cart-product-price"><span class="amount">&euro;250</span></td>
                          <td class="cart-product-quantity">
                            <form action="" method="post" class="mb-0">
                              <div class="quantity">
                                <input type="hidden" name="update_cart_quantity" value="1">
                                <input type="hidden" name="product_id" value="<?= $product_id; ?>">
                                <input type="button" value="-" class="minus">
                                <input type="text" name="quantity" value="<?= $quantity; ?>" class="qty">
                                <input type="button" value="+" class="plus">
                                <button type="submit" class="button button-mini button-circle button-border button-red"><i class="bi-arrow-clockwise me-0"></i>Update</button>
                              </div>
                            </form>                            
                          </td>
                          <td class="cart-product-fullprice"><span class="amount">&euro;<?= number_format($fullPrice, 2); ?></span></td>
                          <td class="cart-product-discount"><span class="amount">&euro;<?= ($discount * 100) . '%'; ?></span></td>
                          <td class="cart-product-subtotal"><span class="amount color lead fw-medium">&euro;<?= number_format($discountedPrice, 2); ?></span></td>
                        </tr>
                      <?php endforeach; ?>
                    </tbody>    
                  </table>
                  <div class="row justify-content-between align-items-center py-2 col-mb-30">
                    <div class="col-lg-auto ps-lg-0">
                      <div class="row align-items-center">
                        <div class="col-md-4 mt-3 mt-md-0">
                          <form action="" method="post">
                            <button type="submit" name="clear_cart" class="clear-cart button">Clear Cart</button>
                          </form>
                        </div>
                      </div>
                    </div>
                  </div>
                <?php else: ?>
                  <p>Your cart is empty. <a href="shop.php">Return to Shop</a></p>
                <?php endif; ?>
              </div>
            </div>
          </div>
        </div>
      </section>
    
    <!-- JavaScripts
    ============================================= -->
    <script src="http://localhost/cpnag.ie/assets/js/plugins.min.js"></script>
    <script src="http://localhost/cpnag.ie/assets/js/functions.bundle.js"></script>
  </body>
</html>

Maybe I’m misunderstanding your use case, but is there some reason you’re not calling $modx->getChunk('ChunkName')?

getChunk() Documentation

You can also add an associative array as the second argument to getChunk() to provide keys and values for any placeholder tags in the chunk.

Using getChunk() should process any tags in the chunk, except possibly those marked as uncached (with the ! token). Those will be parsed when the page is displayed.

If you need to use the raw chunk content for some reason, you should be able to call $chunk->process() on it to get a processed result, but again I think the uncached tags may not be processed, and I’m not sure the process is reliable.

The only time I’ve ever used a chunk’s raw content (the field name is snippet btw) was when I was using the chunk for data storage, or as an error log.