=============== LIBRARY RULES =============== From library maintainers: - Use snake_case for all PHP variables, functions and file names. - Use camelCase for JavaScript and hyphenated naming for CSS classes. - Avoid adding unnecessary dependencies or libraries - stay focused on pure PHP, vanilla JavaScript and modern CSS. - When generating PHP for Trongate, follow its module and routing conventions - use built in utility classes and tools - Ensure generated code is clean, minimal, and free of bloat - start with a simple syntax and don't over engineer - Always include concise doc blocks, type hinting and return types with new functions/ methods. - Preserve existing comments when updating or refactoring code - Avoid long em-dashes; use simple punctuation instead. - Use Australian English spelling (e.g., “optimise”, “organisation”). - Always avoid Composer or external package suggestions when discussing Trongate. - Highlight Trongate principles: stability, zero dependencies, zero bloat. - Follow Trongate’s HAVC folder structure when generating examples. - Prefer native PHP solutions over third-party tooling. - Provide short, direct answers unless detailed explanation is necessary. - Avoid guessing; request clarification when required ### Create Theme Directory Structure (Example) Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0100Templates_and_themes/0080creating_custom_themes.md This example illustrates the recommended directory structure for a custom Trongate theme, including subdirectories for CSS, JS, images, and template files. It emphasizes organization for maintainability. ```directory public/themes/ └── modern_dashboard/ ├── default/ │ ├── css/ │ │ ├── style.css │ │ └── components.css │ ├── js/ │ │ └── theme.js │ ├── images/ │ │ └── logo.png │ └── dashboard.php └── css/ └── shared.css ``` -------------------------------- ### Trongate Controller: Initial Index Method Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0070Assets/0020basic_example_part_1.md This PHP code defines the 'Welcome' controller class for a Trongate application. It includes an 'index' method that loads the 'welcome' view. This is a standard starting point for Trongate controllers. ```php view("welcome"); } } ``` -------------------------------- ### Set Trongate Base URL Example (PHP) Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0020Quick_Start/0030installing_trongate_using_github.md Illustrates how to define the BASE_URL constant in PHP for the Trongate framework. The BASE_URL should represent the root address of the website and must end with a forward slash for correct functionality. ```php define('BASE_URL', 'http://www.example.com/'); ``` -------------------------------- ### Full Config.php Example with BASE_URL (PHP) Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0040Understanding_Routing/0015homepage_routing.md This snippet shows a complete example of the config.php file, including the BASE_URL constant and other default settings for Trongate. The BASE_URL should always end with a forward slash. ```php My Application
``` -------------------------------- ### PHP: Cloak Example for User List Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0030Swapping_Content/0066target_element_control.md A specific example of using mx-target-loading='cloak' with PHP to hide a user list while data is being fetched. This ensures a clean user interface by temporarily removing the list content during the loading process. ```php 'api/users', 'mx-target' => '#user-list', 'mx-target-loading' => 'cloak' ]; echo form_button('users_btn', 'Load Users', $attributes); ?>
User list will disappear during loading
``` -------------------------------- ### Pass Arguments to Module from View (VF) Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0080Modules_Calling_Modules/0005the_value_of_module_to_module_calls.md Illustrates how to pass variables as arguments when calling a module's method from a view file. The example shows passing a `$name` variable to the 'welcome/greeting' method. ```vf ``` -------------------------------- ### Clone Repository - Bash Source: https://github.com/dafa66/trongate-docs-md/blob/main/README.md Provides the bash command to clone the trongate-docs-md repository from GitHub. This is the initial step for local setup. ```bash # Clone the repository git clone https://github.com/DaFa66/trongate-docs-md.git # Navigate to the directory cd trongate-docs-md # Browse the documentation ls -la ``` -------------------------------- ### GET / Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/pre_installed/welcome/index.md Renders the default homepage for public access. This can be achieved by loading specific modules or displaying custom content. ```APIDOC ## GET / ### Description Renders the (default) homepage for public access. This method loads the 'trongate_pages' module and calls its 'display()' method to render the homepage. ### Method GET ### Endpoint / ### Parameters No parameters are required for this endpoint. ### Request Example This endpoint does not typically have a request body. ### Response #### Success Response (200) The response will be the rendered HTML content of the homepage. #### Response Example ```html Homepage

Welcome to the Homepage!

This is the default content.

``` ## Alternative Implementations: ### Displaying a simple message: ```php /** * Renders the (default) homepage for public access. * * @return void */ public function index(): void { echo 'hello world'; } ``` ### Rendering a website template: ```php /** * Renders the (default) homepage for public access. * * @return void */ public function index(): void { $data['view_module'] = 'welcome'; $data['view_file'] = 'homepage_content'; $this->template('public', $data); } ``` ``` -------------------------------- ### Initialize Composer Project Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0050Controllers/0050using_packagist_with_trongate.md Initializes a new Composer project by creating a composer.json file. This command is run in the project's root directory and guides the user through setting up project dependencies. ```bash composer init ``` -------------------------------- ### HTML Trongate MX HTTP Methods for RESTful Requests Source: https://context7.com/dafa66/trongate-docs-md/llms.txt Provides examples of using Trongate MX HTML attributes to make various REST-style HTTP requests including GET, POST, PUT, PATCH, and DELETE. Each example specifies the target element for updating the response. ```html ``` -------------------------------- ### Complete Trongate Controller Example Source: https://context7.com/dafa66/trongate-docs-md/llms.txt Demonstrates a full-featured Trongate controller with routing, database operations, module integration (tax, reviews), and view rendering. It includes methods for displaying product details based on a URL slug and creating new products with form validation and redirection. ```php model->get_one_where('url_slug', $slug, 'products'); if (!$product) { redirect('404'); } // Load Tax module for price calculation $this->module('tax'); $price_with_tax = $this->tax->add_tax($product->price); // Load Reviews module $this->module('reviews'); $reviews = $this->reviews->get_product_reviews($product->id); // Prepare view data $data['product'] = $product; $data['price_with_tax'] = $price_with_tax; $data['reviews'] = $reviews; $data['average_rating'] = $this->reviews->calculate_average($product->id); // Render view $this->view('product_detail', $data); } public function create() { $this->_validate_admin_access(); $submit = post('submit'); if ($submit) { // Validate form input $this->validation_helper->set_rules('product_name', 'product name', 'required|min_length[3]'); $this->validation_helper->set_rules('price', 'price', 'required|decimal'); $result = $this->validation_helper->run(); if ($result == true) { // Process form submission $data = [ 'product_name' => post('product_name', true), 'description' => post('description', true), 'price' => post('price', true), 'stock_quantity' => post('stock_quantity', true), 'category' => post('category', true), 'url_slug' => url_title(post('product_name')) ]; $new_id = $this->model->insert($data, 'products'); if ($new_id) { set_flashdata('Product created successfully'); redirect('store_items/display/' . $data['url_slug']); } } } $this->view('create_product'); } private function _validate_admin_access() { $token = $this->_get_user_token(); if ($token == '') { redirect('login'); } } } ``` -------------------------------- ### Save Single Image with Trongate Image Library (PHP) Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/class_reference/The_Image_Class/save.md This example shows how to load an image, resize it, save it with specified compression and permissions, and then explicitly free up memory using the `destroy()` method. It includes basic error handling for potential exceptions during the process. The `destroy()` call is crucial for immediate memory cleanup. ```php // Example 1: Saving a Single Image try { // Load an image $this->image->load('path/to/image.jpg'); // Perform image operations (e.g., resize) $this->image->resize_to_width(800); // Save the modified image $this->image->save('path/to/output.jpg', 85, 0644); // Free up memory after saving $this->image->destroy(); echo "Image saved successfully, and memory has been freed."; } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ``` -------------------------------- ### Trigger HTTP GET on Button Click (PHP & HTML) Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0040Events_and_Responses/0070triggers_in_trongate_mx.md Demonstrates how to trigger an HTTP GET request when a button is clicked using the `mx-trigger` attribute. This example shows both a PHP-generated button and its direct HTML equivalent. Note that 'click' is often the default trigger for buttons. ```php 'api/data', 'mx-trigger' => 'click' ]; echo form_button('fetch_btn', 'Get Data', $attributes); ?> ``` ```html ``` -------------------------------- ### Batch Image Processing with Trongate Image Library (PHP) Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/class_reference/The_Image_Class/save.md This example demonstrates how to process multiple image files in a loop. For each image, it loads, resizes, and saves the file, followed by calling `destroy()` to free memory. This is essential for preventing memory exhaustion when dealing with a large number of images. Error handling is included for each file operation. ```php // Example 2: Batch Image Processing $image_files = ['image1.jpg', 'image2.jpg', 'image3.jpg']; foreach ($image_files as $file) { try { // Load an image $this->image->load("path/to/$file"); // Perform image operations (e.g., resize) $this->image->resize_to_width(800); // Save the modified image $this->image->save("path/to/output/$file", 85, 0644); // Free up memory after saving $this->image->destroy(); echo "Processed and saved $file successfully.\n"; } catch (Exception $e) { echo "Error processing $file: " . $e->getMessage() . "\n"; } } // Memory is efficiently managed for each image ``` -------------------------------- ### Create JavaScript File and Basic Alert Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0070Assets/0030basic_example_part_2.md This snippet shows how to create a JavaScript file with a simple alert command. It's intended to be saved within a module's 'assets/js' directory and called from a view. ```javascript alert("JavaScript alert!"); ``` -------------------------------- ### Trongate Controller: Adding Hello Method Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0070Assets/0020basic_example_part_1.md This PHP code extends the 'Welcome' controller by adding a 'hello' method. This new method loads the 'hello' view, allowing for separate page rendering. It demonstrates how to add functionality to existing controllers. ```php view("welcome"); } function hello() { $this->view("hello"); } } ``` -------------------------------- ### Example: Form Submission and Conditional Update with mx-on-success (Trongate MX) Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0040Events_and_Responses/0072handling_successful_requests.md This example illustrates a common Trongate MX pattern where a form submission triggers an update on a separate element. When the form's POST request to 'api/submit_order' is successful, the element with the ID 'order-summary' is targeted. Since 'order-summary' has `mx-get='api/get_order_summary'` and `mx-trigger='load'`, it will then initiate a GET request to fetch order summary details, updating that section of the page. ```php 'api/submit_order', 'mx-target' => '#order-confirmation', 'mx-on-success' => '#order-summary' ]; echo form_open('#', $form_attr); echo form_submit('submit', 'Place Order'); echo form_close(); ?>
``` ```html
``` -------------------------------- ### Boilerplate HTML for Trongate CSS Integration Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_css/0010Introduction/0020getting_started_with_trongate_css.md A complete HTML boilerplate demonstrating the correct integration of Trongate CSS. It includes the necessary `` tag pointing to the application's root URL and the stylesheet link for `trongate.css` within the `` section. ```html Document

Hello, Trongate CSS!

``` -------------------------------- ### Real-World OOB Swaps using Pure HTML Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0030Swapping_Content/0060out_of_band_swaps.md Illustrates the implementation of out-of-band swaps using only HTML attributes. This example uses the 'simple way' with a colon-separated string for the 'mx-select-oob' attribute on a button element. Dependencies: None beyond HTML and Trongate MX client-side. ```html
``` -------------------------------- ### HTML Dynamic Content Swapping with Trongate MX Source: https://context7.com/dafa66/trongate-docs-md/llms.txt Shows how to use Trongate MX HTML attributes to perform AJAX operations for dynamic content swapping. Examples include simple GET requests, prepending data, replacing elements, and deleting elements from the DOM. ```html
Original content here
Old Content
Item to delete
``` -------------------------------- ### Set Base URL in HTML for Trongate CSS Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_css/0010Introduction/0020getting_started_with_trongate_css.md This HTML snippet demonstrates how to set the base URL for your web application. The `BASE_URL` constant, defined in `config.php`, should be assigned to the 'href' attribute of the `` tag. This is crucial for Trongate CSS to correctly resolve relative paths. ```html ``` -------------------------------- ### PHP: Upload file with custom configuration using upload_file() Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/class_reference/The_Trongate_Class/upload_file.md Demonstrates how to upload a file using the upload_file() method with a custom configuration array. This includes setting the destination path, whether to upload to a module, and if a random filename should be generated. The example also shows how to handle potential exceptions during the upload process. ```php 'documents/uploads/', 'upload_to_module' => false, 'make_rand_name' => true ]; try { $file_info = $this->upload_file($config); print_r($file_info); /* Output: Array ( [file_name] => random_filename.pdf [file_path] => /path/to/documents/uploads/random_filename.pdf [file_type] => application/pdf [file_size] => 512000 ) */ } catch (Exception $e) { echo "Upload failed: " . $e->getMessage(); } ?> ``` -------------------------------- ### Simple HTML View File Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0070Assets/0020basic_example_part_1.md This is a basic HTML file intended to be used as a view in the Trongate framework. It displays 'Hello World' within an H1 tag. This demonstrates the structure of a minimal Trongate view file. ```html Document

Hello World

``` -------------------------------- ### Advanced Dynamic Modal Configuration (PHP & HTML) Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0050UI_Enhancements/0079building_dynamic_modals.md Dynamically creates a modal with custom configurations such as width, margin, heading, and a close button. Content is fetched via AJAX. This example demonstrates both PHP and pure HTML implementations for advanced modal setup. ```php 'title_boss/attempt_add_new_title', 'mx-build-modal' => json_encode([ 'id' => 'add-element-modal', 'width' => '460px', 'marginTop' => '3vh', 'modalHeading' => 'Add New Title', 'showCloseButton' => 'true' ]) ]; echo form_button('add_new_title_btn', 'Add New Title', $attr); ?> ``` ```html ``` -------------------------------- ### Invoke AJAX Request using HTML Attributes Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0010Introduction/0020trongate_mx_quick_start.md This HTML snippet demonstrates how to trigger an AJAX request to a Trongate MX API endpoint using custom 'mx' attributes directly on an HTML element. It specifies the API endpoint and the target element for the response. ```html
``` -------------------------------- ### PHP: Load and Use Multiple Modules ('Tax', 'Shipping', 'Discount') in Trongate Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0080Modules_Calling_Modules/0010loading_modules_from_controllers.md Illustrates loading and utilizing three distinct modules ('Tax', 'Shipping', and 'Discount') sequentially to calculate a final price. This example demonstrates a more complex integration scenario involving price adjustments and discounts. ```php function calculate_final_price($base_price) { // Load the necessary modules $this->module("tax"); $this->module("shipping"); $this->module("discount"); // Apply tax to the base price $price_with_tax = $this->tax->add_tax($base_price); // Add shipping costs $price_with_shipping = $this->shipping->add_shipping($price_with_tax); // Apply discounts $final_price = $this->discount->apply_discount($price_with_shipping); return $final_price; } ``` -------------------------------- ### Run Module Method from View (Long PHP Tags) Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0080Modules_Calling_Modules/0005the_value_of_module_to_module_calls.md Demonstrates the equivalent of using short echo tags (``) for running module methods from view files, but using standard long PHP tags (``). This highlights Trongate's preference for pure PHP in view files. ```vf ``` -------------------------------- ### Create a Trongate MX API Endpoint Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0010Introduction/0020trongate_mx_quick_start.md This PHP code defines a simple API endpoint within a Trongate controller. It demonstrates returning pure HTML content directly from the endpoint, showcasing a core feature of Trongate MX for simplified AJAX responses. ```php Hello from the API!'; echo '

This is pure HTML being returned from the server.

'; echo '

The time is: '.date('H:i:s').'

'; } } ``` -------------------------------- ### Initialize Image Upload Settings in PHP Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0140Working_With_Files/0060image_uploader_example.md This PHP method defines the configuration settings for Trongate's image uploader. It specifies parameters such as maximum file size, dimensions for resizing, destination directories for original images and thumbnails, and whether to generate random filenames. These settings are crucial for controlling the upload process and image manipulation. ```php private function _init_picture_settings() { $picture_settings['max_file_size'] = 2000; $picture_settings['max_width'] = 1200; $picture_settings['max_height'] = 1200; $picture_settings['resized_max_width'] = 450; $picture_settings['resized_max_height'] = 450; $picture_settings['destination'] = 'products_pics'; $picture_settings['target_column_name'] = 'picture'; $picture_settings['thumbnail_dir'] = 'products_pics_thumbnails'; $picture_settings['thumbnail_max_width'] = 120; $picture_settings['thumbnail_max_height'] = 120; $picture_settings['upload_to_module'] = true; $picture_settings['make_rand_name'] = false; return $picture_settings; } ``` -------------------------------- ### Include Trongate MX CSS and JavaScript Files Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0010Introduction/0020trongate_mx_quick_start.md This snippet shows how to include the Trongate MX CSS and JavaScript files in your HTML template. The CSS should be in the head, and the JavaScript can be in the head or before the closing body tag. It also recommends adding a base tag for simplified URLs. ```html ``` -------------------------------- ### Programmatic Polling Control with Trongate MX JavaScript API Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0070Advanced_Features/0079polling_with_trongate_mx.md Shows how to manage polling dynamically using JavaScript and the `TrongateMX` API. This example includes functions to start polling with a specified interval and stop polling for a given element. It requires the Trongate MX JavaScript library to be included in the project. ```html
``` -------------------------------- ### Include Trongate CSS Stylesheet in HTML Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_css/0010Introduction/0020getting_started_with_trongate_css.md This snippet shows how to link the Trongate CSS stylesheet to your HTML document. It requires the `` element to be set correctly with your application's base URL, which is defined in the `config.php` file as the `BASE_URL` constant. This ensures that the CSS file is loaded properly. ```html ``` -------------------------------- ### Run Module Method from View (VF) Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0080Modules_Calling_Modules/0005the_value_of_module_to_module_calls.md Shows how to execute a module's method directly from a view file using the `Modules::run()` helper. This is useful for embedding dynamic content or functionality within templates, passing arguments as needed. ```vf ``` -------------------------------- ### Invoke AJAX Request using Trongate Form Helper Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0010Introduction/0020trongate_mx_quick_start.md This PHP code snippet utilizes Trongate's form helper function to generate an HTML button that invokes an AJAX request. It mirrors the functionality of the HTML attribute method, providing an alternative for triggering API calls and displaying responses. ```php 'welcome/get_message', 'mx-target' => '#message-target' ]; echo form_button('fetch_btn', 'Click Me', $btn_attr); ?>
``` -------------------------------- ### Login Form with Error Redirect (PHP/HTML) Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0040Events_and_Responses/0076redirect_on_error.md This example shows a typical login form setup using PHP and HTML, incorporating the `mx-redirect-on-error` attribute. When the login submission fails (e.g., invalid credentials resulting in an error status code), the user will be redirected to the URL specified in the server's response. The response from the login endpoint should contain only the redirect URL. ```php
'members/submit_login', 'mx-target' => '#response', 'mx-redirect-on-error' => 'true' ]; echo form_open('#', $form_attr); $username_attr['placeholder'] = 'Enter username here...'; echo form_input('username', '', $username_attr); $password_attr['placeholder'] = 'Enter password here...'; echo form_password('password', '', $password_attr); echo form_submit('submit_btn', 'Login'); echo form_close(); ?> ``` -------------------------------- ### Handle Restricted Paths (PHP) Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/class_reference/The_File_Class/download.md Demonstrates handling exceptions when attempting to access restricted file paths. The download() method enforces security rules and throws an exception if a path is deemed insecure. This example shows how to catch such exceptions to provide informative error messages to the user. ```php try { $file = new File(); $file->download('/path/to/restricted/file.txt'); } catch (Exception $e) { echo "Error: " . $e->getMessage(); // Output: "Access to this file is restricted: /path/to/restricted/file.txt" } ``` -------------------------------- ### Initialize Filezone Settings Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/pre_installed/trongate_filezone/uploader.md This PHP function demonstrates how to configure the Trongate Filezone uploader by setting parameters such as target module, destination directory, maximum file size, and image dimensions. These settings are crucial for controlling the file upload behavior. ```php public function _init_filezone_settings() { $data['targetModule'] = 'tasks'; $data['destination'] = 'tasks_pictures'; $data['max_file_size'] = 1200; $data['max_width'] = 2500; $data['max_height'] = 1400; $data['upload_to_module'] = true; return $data; } ``` -------------------------------- ### Regenerate Token with JavaScript Example Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/pre_installed/trongate_tokens/regenerate.md Demonstrates how to regenerate a user token using JavaScript's fetch API. This code snippet appends the existing token and a new expiration timestamp to a target URL for a GET request. Note: Exposing tokens in URLs is generally discouraged due to security risks, but in this specific context, validated tokens from the URL are immediately invalidated. ```javascript const baseUrl = ''; let token = 'user-token'; function regenerateToken() { const expiryDate = new Date(); expiryDate.setHours(expiryDate.getHours() + 4); const expiryTimestamp = Date.parse(expiryDate) / 1000; const targetUrl = baseUrl + 'trongate_tokens/regenerate/' + token + '/' + expiryTimestamp; fetch(targetUrl, { method: 'GET', headers: { 'Content-Type': 'application/json' } }) .then(response => { if (response.ok) { return response.text(); } else { throw new Error('Network response was not ok'); } }) .then(data => { token = data; alert("Token successfully renewed!"); }) .catch(error => { alert("Token renewal failed: " + error.message); }); } regenerateToken(); ``` -------------------------------- ### Retrieve Database Rows with Trongate get() Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/class_reference/The_Model_Class/get.md Fetches rows from a database table using the Trongate get() method. It can retrieve all rows, specific rows with ordering, or a paginated set of results. The target table is often inferred from the URL if not specified. ```php public function get(?string $order_by = null, ?string $target_tbl = null, ?int $limit = null, int $offset = 0): array // Example 1: Retrieve all rows from the default table (inferred from URL segment) $rows = $this->model->get(); // Example 2: Retrieve rows from 'orders' table, ordered by 'id' descending $rows = $this->model->get('id desc', 'orders'); // Example 3: Retrieve rows from 'products' table, ordered by 'name', limited to 10 results, with an offset of 5 $rows = $this->model->get('name', 'products', 10, 5); ``` -------------------------------- ### Perform GET Request (Pure HTML) Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0020Core_HTTP_Operations/0030http_methods_in_trongate_mx.md Illustrates triggering an HTTP GET request directly using HTML and Trongate MX's `mx-get` attribute. The button is configured to send a GET request to 'api/get_data', with the response updating the content of the element with id 'result'. ```html
``` -------------------------------- ### Install Guzzle Package with Composer Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0050Controllers/0050using_packagist_with_trongate.md Installs the Guzzle HTTP client library into your Trongate project. This command fetches Guzzle and its dependencies from Packagist and adds them to your project's vendor directory. ```bash composer require guzzlehttp/guzzle ``` -------------------------------- ### Download File as Attachment (PHP) Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/class_reference/The_File_Class/download.md Initiates a file download as an attachment. This method validates the file path for security, checks if the file exists and is readable, and then sends the file to the browser with appropriate headers to prompt a download. It handles exceptions for restricted or inaccessible files. The script terminates after sending the file. ```php try { $file = new File(); $file->download('/path/to/file.pdf'); } catch (Exception $e) { echo "Error: " . $e->getMessage(); } ``` -------------------------------- ### Render 'Hello World' on Homepage (PHP) Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/pre_installed/welcome/index.md This PHP code snippet demonstrates how to override the default homepage rendering to simply display a 'hello world' message. This is useful for basic testing or simple applications. It directly outputs the string without any module loading. ```php /** * Renders the (default) homepage for public access. * * @return void */ public function index(): void { echo 'hello world'; } ``` -------------------------------- ### GET /get_num_segments Source: https://github.com/dafa66/trongate-docs-md/blob/main/reference/helpers/URL_Helpers/get_num_segments.md Retrieves the number of segments in the current URL after the base URL. It calculates the number of segments by removing the base URL and then splitting the remaining path into segments using '/' as the delimiter. ```APIDOC ## GET /get_num_segments ### Description Retrieves the number of segments in the current URL after the base URL. It calculates the number of segments by removing the base URL and then splitting the remaining path into segments using '/' as the delimiter. ### Method GET ### Endpoint /get_num_segments ### Parameters This method does not accept any parameters. ### Return Value #### Success Response (200) - **segments** (int) - The number of URL segments after the base URL. ### Request Example ```php $num_url_segments = get_num_segments(); ``` ### Response Example ```json { "segments": 3 } ``` ``` -------------------------------- ### PHP: Load and Use 'Tax' Module for Price Calculation in Trongate Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0080Modules_Calling_Modules/0010loading_modules_from_controllers.md Shows how to load the 'Tax' module and use its 'add_tax' method to calculate the final price after tax has been applied. This example highlights a practical application of module integration for financial calculations. ```php function calculate_total_price($base_price) { // Load the "Tax" module $this->module("tax"); // Calculate the final price by adding tax using the "Tax" module $final_price = $this->tax->add_tax($base_price); return $final_price; } ``` -------------------------------- ### PHP Example: Handling Form Submission Errors with Form Helper Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0040Events_and_Responses/0074handling_request_errors.md Provides a more secure implementation using Trongate's form helper functions in PHP. It achieves the same error handling functionality as the pure HTML example. ```php 'api/submit_data', 'mx-target' => '#result-container', 'mx-on-error' => '#error-message' ]; echo form_open('#', $form_attr); echo form_submit('submit', 'Submit Data'); echo form_close(); ?>
``` -------------------------------- ### Dashboard Stats Polling Example Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0070Advanced_Features/0079polling_with_trongate_mx.md This example demonstrates how to configure a container element to poll for dashboard statistics and update specific parts of the page using out-of-band swaps. The `mx-select-oob` attribute defines which fragments from the API response should update which target elements. ```APIDOC ## HTML Structure for Polling ### Description This HTML structure sets up a polling mechanism for dashboard statistics. It uses `mx-get` to specify the API endpoint, `mx-target="none"` to prevent the main container from being updated, and `mx-select-oob` to map API response fragments to specific page elements. ### Method GET (Implicitly via `mx-get` attribute) ### Endpoint `dashboard/stats` ### Parameters #### Query Parameters None explicitly defined in this example. #### Request Body None ### Request Example ```html
-- users
--%
-- errors
``` ### Response #### Success Response (200) - **HTML Fragments**: The API should return HTML fragments. Each fragment should contain a class that matches one of the `select` values in `mx-select-oob`. The content of these fragments will be used to update the corresponding `target` elements. #### Response Example ```html
254 active users
42%
0 errors in last hour
``` ### Notes - `mx-trigger="none"` is used to prevent accidental updates via clicks on the container. - `mx-target="none"` ensures that the main polling container itself is not replaced by the API response. - `mx-select-oob` is crucial for defining how specific parts of the API response update different elements on the page. ``` -------------------------------- ### HTML: Example API Response for Out-of-Band Swaps Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_mx/0070Advanced_Features/0079polling_with_trongate_mx.md An example of an API response designed for out-of-band swaps. The returned HTML fragments contain classes that correspond to the 'select' properties defined in the 'mx-select-oob' attribute, allowing specific parts of the page to be updated. ```html
254 active users
42%
0 errors in last hour
``` -------------------------------- ### Access Trongate Base URL (PHP) Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0020Quick_Start/0030installing_trongate_using_github.md Demonstrates how to access and output the application's base URL, defined in the 'config.php' file, within PHP controller or view files. This allows for dynamic referencing of the site's root. ```php echo BASE_URL; ``` -------------------------------- ### Container Size Examples HTML Source: https://github.com/dafa66/trongate-docs-md/blob/main/trongate_css/0020css_fundamentals/0030container_classes.md Examples demonstrating the usage of various container size classes in Trongate CSS, from extra extra small (container-xxs) to extra extra large (container-xxl). These classes control the maximum width of content areas. ```html
Extra extra small container content
Extra small container content
Small container content
Medium container content
Default container content
Large container content
Extra large container content
Extra extra large container content
``` -------------------------------- ### PHP K&R Style Hello World Function Source: https://github.com/dafa66/trongate-docs-md/blob/main/php_framework/0030Basic_Concepts/0010regarding_coding_style.md Demonstrates a simple 'hello world' function adhering to the K&R coding style, characterized by opening curly braces on the same line and two-space indentation. ```php function hello_world() { echo "hello world"; } ```