### Search Form Example with GET Method using Trongate Form Helper Source: https://trongate.io/documentation/trongate_php_framework/form-handling/creating-forms This example demonstrates creating a search form that uses the GET HTTP method. It includes setting the method to 'get' and adding a CSS class to the form, along with a search input and submit button. ```php $attributes = [ 'method' => 'get', 'class' => 'search-form' ]; echo form_open('products/search', $attributes); echo form_search('q', '', ['placeholder' => 'Search products...']); echo form_submit('submit', 'Search'); echo form_close(); ``` -------------------------------- ### PHP Constructor: Example with Initialization Source: https://trongate.io/documentation/trongate_php_framework/tips-and-best-practices/mastering-constructors Provides a PHP example of a class constructor that performs initialization tasks. It demonstrates setting a class property (`$items_per_page`) based on configuration after ensuring the parent constructor is called first. ```php items_per_page = 50; } public function index() { // items_per_page is already set echo "Displaying " . $this->items_per_page . " items per page"; } } ``` -------------------------------- ### Display File Details in PHP Source: https://trongate.io/documentation/trongate_php_framework/working-with-files/file-management-beyond-uploads This example demonstrates using the `info()` method to fetch file metadata and display it to the user. It first retrieves file record details from the database, constructs the file path, checks if the file exists, and then calls `info()` to get the metadata. This information is then passed to a view for display. ```PHP public function view_file_info($file_id): void { $file = $this->db->get_where($file_id, 'documents'); if ($file === false) { redirect('documents/not_found'); } $file_path = '../modules/documents/storage/' . $file->filename; if ($this->file->exists($file_path)) { $info = $this->file->info($file_path); $data['file_record'] = $file; $data['file_info'] = $info; $data['view_file'] = 'file_details'; $this->view('file_details', $data); } else { redirect('documents/not_found'); } } ``` -------------------------------- ### Real-World User Controller Example in Trongate PHP Source: https://trongate.io/documentation/trongate_php_framework/module-fundamentals/controller-files Provides a practical example of a user controller in Trongate, demonstrating how to fetch user data from the database and display it using views. It showcases the URL-to-method mapping for index and profile actions. ```php db->get('id', 'desc'); $this->view('users_list', $data); } function profile($user_id) { $user = $this->db->get_where($user_id); $this->view('user_profile', $user); } } ``` -------------------------------- ### Real-World Task Due Date Example (PHP Controller) Source: https://trongate.io/documentation/trongate_php_framework/working-with-dates-and-times/date-input-fields Provides a controller example for creating a task, including setting the form location and handling form submission with validation. It uses `post()` to retrieve data and `validation->run()` to check validity, redirecting on success or redisplaying the form on failure. ```PHP public function create(): void { $data['headline'] = 'Create Task'; $data['due_date'] = post('due_date', true); $data['form_location'] = BASE_URL . 'tasks/submit'; $this->templates->admin($data); } public function submit(): void { $this->validation->set_rules('task_title', 'task title', 'required'); $this->validation->set_rules('due_date', 'due date', 'required|valid_date'); if ($this->validation->run() === true) { $data['task_title'] = post('task_title', true); $data['due_date'] = post('due_date', true); $new_id = $this->db->insert($data, 'tasks'); set_flashdata('Task successfully created'); redirect('tasks/show/' . $new_id); } else { $this->create(); // Redisplay form with errors } } ``` -------------------------------- ### Image Upload Validation Rules and Examples (PHP) Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/image-manipulation-quick-reference This section provides PHP validation rules for image uploads, including requirements for size, dimensions, and examples of how to set these rules using `$this->validation->set_rules()`. It demonstrates setting up rules for avatars and product images. ```php // Avatar requirements: square, 100-2000px, max 2MB $this->validation->set_rules( 'avatar', 'Profile Picture', 'required|max_size[2000]|min_width[100]|min_height[100]|max_width[2000]|max_height[2000]' ); // Product image: flexible size, max 5MB $this->validation->set_rules( 'product_image', 'Product Image', 'required|max_size[5000]|max_width[4000]|max_height[4000]' ); ``` -------------------------------- ### Practical User Profile Display Example (PHP) Source: https://trongate.io/documentation/trongate_php_framework/authorization-and-authentication/validating-and-fetching-user-data This comprehensive example illustrates fetching user data and displaying it on a profile page. It first validates any token, then retrieves the full user object. It proceeds to fetch additional member details from a 'members' table using the user's ID and finally passes all relevant data to a view file for rendering. ```PHP trongate_tokens->attempt_get_valid_token(); if ($token === false) { redirect('login'); } // Get complete user object $user = $this->trongate_tokens->get_user_obj(); // Fetch member details from members table $sql = 'SELECT * FROM members WHERE trongate_user_id = ?'; $member = $this->db->query_bind($sql, [$user->trongate_user_id], 'object'); $member = $member[0] ?? null; if (!$member) { redirect('login'); } // Pass data to view $data['first_name'] = $member->first_name; $data['last_name'] = $member->last_name; $data['username'] = $member->username; $data['user_level'] = $user->user_level; $data['view_file'] = 'profile'; $this->templates->members_area($data); } } ``` -------------------------------- ### POST-Redirect-GET Pattern for Upload Success (PHP) Source: https://trongate.io/documentation/trongate_php_framework/working-with-files/basic-file-uploading Illustrates the correct implementation of the POST-Redirect-GET pattern in Trongate. The 'wrong' example shows direct view rendering which can cause form resubmission issues on refresh. The 'right' example uses `set_flashdata` and `redirect` for a clean user experience. ```php // ❌ WRONG - causes "resubmit form?" on refresh if ($result === true) { $data['filename'] = $file_info['file_name']; $this->view('upload_success', $data); // Don't do this! } // ✅ RIGHT - clean refresh, no duplicate uploads if ($result === true) { set_flashdata('File uploaded successfully!'); redirect('simple_uploader/success/' . $file_info['file_name']); } ``` -------------------------------- ### Complete Order Processing Example with Modules Source: https://trongate.io/documentation/trongate_php_framework/database-operations/loading-modules-from-models A comprehensive example of a Trongate model processing an order. It showcases automatic database access (`$this->db`, `$this->analytics`) alongside explicit module loading for 'tax' and 'email_sender' to perform calculations and send confirmations. ```php db->get_where($order_id, 'orders'); if (!$order) { return false; } // 2. Calculate tax using Tax module (requires loading) $this->module('tax'); $tax_amount = $this->tax->calculate($order->subtotal, $order->state); // 3. Update order total in database (automatic) $update_data = [ 'tax_amount' => $tax_amount, 'total' => $order->subtotal + $tax_amount, 'processed_at' => time() ]; $this->db->update($order_id, $update_data, 'orders'); // 4. Send confirmation email (requires loading) $this->module('email_sender'); $this->email_sender->send( $order->customer_email, 'Order Confirmation', $this->build_confirmation_email($order, $tax_amount) ); // 5. Log to analytics database (automatic) $analytics_data = [ 'order_id' => $order_id, 'amount' => $update_data['total'], 'timestamp' => time() ]; $this->analytics->insert($analytics_data, 'order_events'); return true; } private function build_confirmation_email($order, $tax_amount) { $message = "Thank you for your order #" . $order->id . "\n\n"; $message .= "Subtotal: $" . number_format($order->subtotal, 2) . "\n"; $message .= "Tax: $" . number_format($tax_amount, 2) . "\n"; $message .= "Total: $" . number_format($order->subtotal + $tax_amount, 2); return $message; } } ``` -------------------------------- ### PHP Function Example: Simple vs. Modern Syntax Source: https://trongate.io/documentation/trongate_php_framework/basic-concepts/regarding-modern-php-syntax Demonstrates two ways to write a PHP function to retrieve user data. The first uses simpler syntax for clarity in documentation, while the second employs modern PHP features like type hints and doc blocks for production code. This highlights Trongate's support for modern PHP while prioritizing ease of understanding in examples. ```php function get_user($id) { $user_obj = $this->db->get_where($id, 'users'); return $user_obj(); } ``` ```php /** * Retrieve a user record by ID. * * @param int $id The unique identifier of the user. * @return object|bool Returns a user object if found, or false on failure. */ public function get_user(int $id): object|bool { $user_obj = $this->db->get_where($id, 'users'); return $user_obj(); } ``` -------------------------------- ### Login Form Example using Trongate Form Helper Source: https://trongate.io/documentation/trongate_php_framework/form-handling/creating-forms A practical example of creating a complete login form using various Trongate Form Helper functions. It includes labels, email input with attributes, password input, submit button, and form closing. ```php echo form_open('auth/login'); echo form_label('Email'); $email_attr = ['placeholder' => 'Enter your email address', 'autocomplete' => 'email']; echo form_email('email', '', $email_attr); echo form_label('Password'); echo form_password('password', '', array('placeholder' => 'Enter password')); echo form_submit('submit', 'Log In'); echo form_close(); ``` -------------------------------- ### Custom Routing Configuration Example Source: https://trongate.io/documentation/trongate_php_framework/module-fundamentals/importing-sql Shows how to configure custom routes in Trongate Control, which can trigger the control process for specific modules. ```php // config/custom_routing.php $routes = [ 'admin' => 'trongate_administrators/login' ]; ``` -------------------------------- ### Trongate Image Module: Stateful Workflow Example (PHP) Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/meet-the-image-module Demonstrates the typical stateful workflow for the Trongate Image module in PHP. This includes loading an image (via upload or file path), performing manipulations like resizing and cropping, and finally saving the modified image to disk or outputting it directly to the browser. Ensure the Image module is initialized before use. ```php // 1. GET IMAGE INTO MEMORY // Option A: Upload a new image $file_info = $this->image->upload($config); // Option B: Load an existing image $this->image->load('modules/gallery/photos/landscape.jpg'); // 2. MANIPULATE it (any combination of operations) $this->image->resize_to_width(800); $this->image->crop(400, 400, 'center'); // 3. Either SAVE to disk... $this->image->save('modules/gallery/photos/landscape_thumb.jpg', 85); // ...or OUTPUT directly to browser header('Content-Type: ' . $this->image->get_header()); $this->image->output(); ``` -------------------------------- ### Invoke AJAX Request using HTML Attributes Source: https://trongate.io/documentation/trongate_mx/introduction/trongate-mx-quick-start This snippet shows how to invoke an AJAX GET request using only HTML and Trongate MX attributes. The 'mx-get' attribute specifies the API endpoint, and 'mx-target' defines the element where the response will be inserted. No JavaScript is required. ```html
``` -------------------------------- ### File Upload Workflow Example Source: https://trongate.io/documentation/trongate_php_framework/working-with-files/file-handling-quick-reference Demonstrates a common three-method pattern for handling file uploads with validation. ```APIDOC ## Common Patterns ### Pattern 1: Basic Upload with Validation This example illustrates a typical file upload workflow using a three-method pattern for clarity and separation of concerns. It includes validation and redirection to prevent duplicate submissions. #### Method 1: Display Upload Form ```php function upload_form() { // Load the view to display the upload form $this->view('upload_form'); } ``` #### Method 2: Process Upload ```php function submit_upload() { // Set validation rules for the file upload $this->validation->set_rules('userfile', 'File', 'required|allowed_types[pdf]|max_size[5000]'); // Run the validation $result = $this->validation->run(); if ($result === true) { // If validation passes, configure upload settings $config['destination'] = 'uploads'; // Directory to upload to $config['upload_to_module'] = true; // Upload to module specific directory // Perform the file upload $file_info = $this->file->upload($config); // Set a success flash message set_flashdata('File uploaded successfully'); // Redirect to a success page, passing the file name redirect('documents/success/' . $file_info['file_name']); } else { // If validation fails, redisplay the upload form (errors will be shown) $this->upload_form(); } } ``` #### Method 3: Show Success Message ```php function success() { // Get the file name from the URL segment $filename = segment(3); $data['filename'] = $filename; // Load the success view with the file name $this->view('upload_success', $data); } ``` **Note on the Three-Method Pattern:** This pattern separates the concerns of displaying the form, processing the upload, and showing a success message. Redirecting after a successful upload prevents accidental re-submission if the user refreshes the page. ``` -------------------------------- ### Invoke AJAX Request using PHP form_button() Helper Source: https://trongate.io/documentation/trongate_mx/introduction/trongate-mx-quick-start This snippet demonstrates how to invoke an AJAX GET request using Trongate's PHP form_button() helper function. It achieves the same functionality as the HTML attribute method by passing 'mx' attributes as an array to the helper. This provides a server-side way to generate AJAX-enabled buttons. ```php 'welcome/get_message', 'mx-target' => '#message-target' ]; echo form_button('fetch_btn', 'Click Me', $btn_attr); ?>
``` -------------------------------- ### Upload, Process, and Save Images with Trongate Image Module (PHP) Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/understanding-image-paths Demonstrates the three-step process for handling images: loading/uploading, processing (resizing), and saving. It emphasizes the use of relative paths for file operations and shows correct and incorrect examples for saving. The `upload()` method is for new uploads, while `load()` is for existing images. ```php // Step 1a: Upload NEW image (config array specifies destination directory) $config = [ 'destination' => 'products', 'upload_to_module' => true ]; $file_info = $this->image->upload($config); // Step 1b: Load EXISTING image (uses relative path) $this->image->load('modules/products/images/original.jpg'); // Step 2: Process (no paths needed - works on loaded image) $this->image->resize_to_width(800); // Step 3: Save (uses relative path) // ✅ CORRECT: Relative path $this->image->save('modules/products/images/resized.jpg'); // ⚠️ WORKS BUT NOT RECOMMENDED: Absolute path $this->image->save('/var/www/html/myapp/modules/products/images/resized.jpg'); // ❌ DOES NOT WORK: URL $this->image->save('https://example.com/products/images/resized.jpg'); // ❌ DOES NOT WORK: Module asset trigger $this->image->save('products_module/images/resized.jpg'); ``` -------------------------------- ### GET Form Example (No CSRF Protection - PHP) Source: https://trongate.io/documentation/trongate_php_framework/form-handling/csrf-protection This snippet shows how to create a form using the GET method with Trongate's form helpers. GET forms do not include CSRF tokens as they are not intended for state-changing operations. ```php 'get']); echo form_search('q', $q); echo form_submit('submit', 'Search'); echo form_close(); // No CSRF token for GET forms ?> ``` -------------------------------- ### Load Modules from Controller (PHP) Source: https://trongate.io/documentation/trongate_php_framework/module-fundamentals/introducing-included-modules Demonstrates loading and using various modules (database, validation, file, image) directly from a PHP controller file in Trongate IO. No external registration or configuration is needed. It shows examples of database queries, validation checks, file uploads, and image resizing. ```php // From any controller – it just works $rows = $this->db->get('products'); $is_valid = $this->validation->run($post); $upload_info = $this->file->upload($config); $resized = $this->image->resize('uploads/pic.jpg', 800, 600); ``` -------------------------------- ### GET Request Example Source: https://trongate.io/documentation/trongate_mx/core-http-operations/http-methods-in-trongate-mx Demonstrates how to make an HTTP GET request when a button is clicked using the 'mx-get' attribute. The response is displayed in a specified target element. ```APIDOC ## GET /api/get_data ### Description Sends an HTTP GET request to the specified endpoint when a button is clicked. The response from the server is then rendered into the element identified by the 'mx-target' attribute. ### Method GET ### Endpoint /api/get_data ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```html
``` ### Response #### Success Response (200) - **content** (string) - The response content from the API endpoint. #### Response Example ```json { "content": "Data received from API" } ``` ``` -------------------------------- ### Upload File and Get Information (PHP) Source: https://trongate.io/documentation/trongate_php_framework/working-with-files/understanding-file-paths Demonstrates how to upload a file using the File module's upload() method with different configuration options. It shows how to specify the destination and whether to upload to the module directory or the public directory. The output includes the file name, relative path, MIME type, and file size. ```php // Example 1: Upload to module directory $config = [ 'destination' => 'documents', 'upload_to_module' => true ]; $file_info = $this->file->upload($config); // Returns: array(4) { // ["file_name"]=> string(11) "report.pdf" // ["file_path"]=> string(42) "../modules/users/documents/report.pdf" // ["file_type"]=> string(15) "application/pdf" // ["file_size"]=> int(245760) // } // Example 2: Upload to public directory $config = [ 'destination' => 'my_uploads' ]; $file_info = $this->file->upload($config); // Returns: array(4) { // ["file_name"]=> string(11) "report.pdf" // ["file_path"]=> string(21) "my_uploads/report.pdf" // ["file_type"]=> string(15) "application/pdf" // ["file_size"]=> int(245760) // } ``` -------------------------------- ### Change HTTP Method for Forms using PHP Source: https://trongate.io/documentation/trongate_php_framework/form-handling/creating-forms This example shows how to change the default HTTP method (POST) to GET for a form using the `form_open()` function. It involves passing an attributes array with the 'method' key set to 'get'. Note that GET forms do not include CSRF tokens. ```php $attributes = ['method' => 'get']; echo form_open('search/results', $attributes); ``` -------------------------------- ### Create Upload Directories (Shell) Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/basic-image-uploading This command-line snippet demonstrates how to create the necessary directories for storing uploaded images and their thumbnails. It uses `mkdir -p` to create parent directories if they don't exist and `chmod` to set the appropriate file permissions for security. ```bash # From your application root: mkdir -p modules/simple_image_uploader/uploads/thumbs chmod 755 modules/simple_image_uploader/uploads chmod 755 modules/simple_image_uploader/uploads/thumbs ``` -------------------------------- ### GET Request with Trongate MX (PHP & HTML) Source: https://trongate.io/documentation/trongate_mx/core-http-operations/http-methods-in-trongate-mx Demonstrates how to initiate an HTTP GET request using Trongate MX. It includes examples using PHP form helper functions and pure HTML attributes. The response of the GET request is displayed in a specified target element. ```php 'api/get_data', 'mx-target' => '#result' ]; echo form_button('get_data_btn', 'Get Data', $attributes); ?>
``` ```html
``` -------------------------------- ### Toggling Polling Based on User Actions Source: https://trongate.io/documentation/trongate_mx/advanced-features/polling-with-trongate-mx This example shows how to dynamically start and stop polling based on user interactions, such as clicking a button. ```APIDOC ## POST /api/start ### Description Initiates an action, likely starting a process or enabling a feature. In this context, it's used to reveal a second area and begin polling. ### Method POST ### Endpoint /api/start ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```html
``` ## GET /api/updates ### Description Fetches updates for a specific area. This endpoint is polled periodically to keep the `#updates` div synchronized. ### Method GET ### Endpoint /api/updates ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```html ``` ### Response #### Success Response (200) Content to be displayed in the `#updates` div. #### Response Example ```html

Latest update information.

``` ``` -------------------------------- ### Upload Image with Configuration (PHP) Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/image-manipulation-quick-reference Demonstrates how to upload an image using the Trongate Image library with various configuration options. This includes setting the destination path, enabling random naming, and defining maximum dimensions for the uploaded image and its thumbnail. The function returns an array containing file details. ```PHP $config = [ 'destination' => 'products/images', 'upload_to_module' => true, 'make_rand_name' => true, 'max_width' => 1200, 'max_height' => 1200, 'thumbnail_dir' => 'products/images/thumbs', 'thumbnail_max_width' => 300, 'thumbnail_max_height' => 300 ]; $file_info = $this->image->upload($config); /* Returns: [ 'file_name' => 'img_6756d8e9a2b4f3.21.jpg', 'file_path' => '../modules/products/products/images/img_6756d8e9a2b4f3.21.jpg', 'file_type' => 'image/jpeg', 'file_size' => 245760, 'thumbnail_path' => '../modules/products/products/images/thumbs/img_6756d8e9a2b4f3.21.jpg' ] */ ``` -------------------------------- ### Load and Process Existing Image (PHP) Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/understanding-image-paths Explains how to load an existing image from a filesystem path, perform processing like resizing, and save the modified image. It also shows how to generate the correct URL for displaying the processed image. ```PHP // Load existing image using filesystem path $source = '../modules/products/images/original.jpg'; $this->image->load($source); // Process the loaded image $this->image->resize_to_width(800); // Save the processed result $this->image->save('../modules/products/images/original_800.jpg'); // Display image using URL (convert filesystem path to browser URL) $url = 'products_module/images/original_800.jpg'; ``` -------------------------------- ### Complete Form Validation Example in PHP Source: https://trongate.io/documentation/trongate_php_framework/working-with-dates-and-times/validating-date-and-time-data A comprehensive example of setting up validation rules for a form submission in PHP, including required fields, date, time, and custom callback validation for end time after start time. It shows the process of running validation and handling success or failure. ```PHP public function submit(): void { // Set validation rules $this->validation->set_rules('event_title', 'event title', 'required|min_length[3]'); $this->validation->set_rules('event_date', 'event date', 'required|valid_date'); $this->validation->set_rules('start_time', 'start time', 'required|valid_time'); $this->validation->set_rules('end_time', 'end time', 'required|valid_time|callback_end_after_start'); if ($this->validation->run() === true) { $data['event_title'] = post('event_title', true); $data['event_date'] = post('event_date', true); $data['start_time'] = post('start_time', true); $data['end_time'] = post('end_time', true); $this->db->insert($data, 'events'); set_flashdata('Event created successfully'); redirect('events/manage'); } else { $this->create(); } } ``` -------------------------------- ### Simplified Trongate MX File Includes with Base Tag Source: https://trongate.io/documentation/trongate_mx/introduction/trongate-mx-quick-start After setting the base tag, you can simplify the inclusion of Trongate MX CSS and JavaScript files. This reduces the need for the BASE_URL constant in your file paths. ```html ``` -------------------------------- ### Crop and Resize-and-Crop Images (PHP) Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/image-manipulation-quick-reference Demonstrates how to crop images to specific dimensions, either from the center, left, or right. It also shows the `resize_and_crop` method, which resizes an image to fit specific dimensions while maintaining aspect ratio and then crops any excess to ensure the exact output size. ```PHP // Simple crop (centered) $this->image->load('modules/blog/images/wide.jpg'); $this->image->crop(800, 600); // Crops from center // Crop from left (preserve left side) $this->image->crop(800, 600, 'left'); // Crop from right (preserve right side) $this->image->crop(800, 600, 'right'); // Perfect fit (resize + crop) $this->image->load('modules/products/images/any-size.jpg'); $this->image->resize_and_crop(400, 300); // Always produces exactly 400×300, no stretching ``` -------------------------------- ### Create a Simple API Endpoint in Trongate MX Source: https://trongate.io/documentation/trongate_mx/introduction/trongate-mx-quick-start This PHP code defines a simple API endpoint within a Trongate controller. It demonstrates how to return raw HTML content directly from the server, showcasing a key feature of Trongate MX. ```php Hello from the API!'; echo '

This is pure HTML being returned from the server.

'; echo '

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

'; } } ``` -------------------------------- ### Complete Login Controller Example (PHP) Source: https://trongate.io/documentation/trongate_php_framework/authorization-and-authentication/generating-tokens A realistic login controller that validates credentials, generates a token based on 'remember me' preference, and redirects the user. ```PHP db->get_where_custom('username', $username, 'members'); // Validate credentials if (!$member || !password_verify($password, $member->password)) { // Invalid login set_flashdata('Invalid username or password'); redirect('members/login'); } // Credentials valid - generate token $token_data = ['user_id' => $member->trongate_user_id]; // If "remember me" checked, use cookie with 30-day expiry if ($remember_me === '1') { $token_data['expiry_date'] = time() + (86400 * 30); $token_data['set_cookie'] = true; } $token = $this->trongate_tokens->generate_token($token_data); // Redirect to members area redirect('members/dashboard'); } } ``` -------------------------------- ### Include Trongate MX CSS and JavaScript Files Source: https://trongate.io/documentation/trongate_mx/introduction/trongate-mx-quick-start This snippet demonstrates 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. Ensure BASE_URL is correctly configured. ```html ``` -------------------------------- ### Run Modules from View File (PHP) Source: https://trongate.io/documentation/trongate_php_framework/module-fundamentals/introducing-included-modules Illustrates how to execute a module's function directly from a Trongate IO view file using the `Modules::run()` method. This allows dynamic content generation within views without complex controller interactions. The example shows running a 'pagination/show' module with provided data. ```php ``` -------------------------------- ### Setting current time as default value in form_time() with PHP Source: https://trongate.io/documentation/trongate_php_framework/working-with-dates-and-times/time-input-fields This example shows how to set the current time as the default value for a time input field generated by the form_time() function. It uses PHP's date() function to get the current time in HH:MM format. ```PHP $now = date('H:i'); echo form_time('clock_in_time', $now); ``` -------------------------------- ### Programmatic Polling Control with JavaScript API Source: https://trongate.io/documentation/trongate_mx/advanced-features/polling-with-trongate-mx This example shows how to control polling dynamically using the Trongate MX JavaScript API. It includes functions to start polling on a specified element with a given interval and to stop polling. This approach offers granular control over when and how data is fetched and updated. ```javascript
``` -------------------------------- ### File Browser View Example (PHP) Source: https://trongate.io/documentation/trongate_php_framework/working-with-files/directory-management This PHP code snippet demonstrates how to display a list of directories and files, typically used in a file browser interface. It iterates through the results from `list_directory()` and formats the output using HTML and PHP functions. ```PHP

Folders

Files

``` -------------------------------- ### Prevent Automatic Polling Trigger with mx-trigger="none" Source: https://trongate.io/documentation/trongate_mx/advanced-features/polling-with-trongate-mx This example demonstrates how to use `mx-trigger="none"` to disable automatic polling on an element, allowing it to be controlled programmatically. It includes HTML for a content area and a button to start polling, along with JavaScript functions to log updates and initiate polling. ```html

This container has content that will be updated through polling.

``` -------------------------------- ### Convert Filesystem Paths to Browser URLs for Module Images (PHP) Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/understanding-image-paths Provides a PHP example of converting a filesystem path stored in a database to a browser-friendly URL using the module asset trigger pattern. This is crucial for displaying module images correctly in HTML. ```php public function view_product(): void { $product_id = segment(3, 'int'); // Get product from database $product = $this->db->get_where($product_id, 'products'); // The database stores the filesystem path // e.g., '../modules/shop/products/laptop.jpg' $filesystem_path = $product->image_path; // Convert to browser URL for display // Remove '../modules/' and replace '/' with '_module/' $browser_url = str_replace('../modules/shop/', 'shop_module/', $filesystem_path); // Pass to view $data['product'] = $product; $data['image_url'] = $browser_url; $this->view('product_detail', $data); } // In the view: // <?= out($product->name) ?> // Renders as: ``` -------------------------------- ### Toggle Polling Based on User Actions Source: https://trongate.io/documentation/trongate_mx/advanced-features/polling-with-trongate-mx This advanced example shows how to toggle polling based on user interactions. Clicking a 'Start' button triggers a POST request, reveals a second area, and initiates polling. A 'Stop Polling' button within the second area halts the polling process. It includes HTML structure and associated JavaScript functions. ```html
``` -------------------------------- ### Dynamic Image Serving with Resizing and Caching (PHP) Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/image-manipulation-quick-reference Serves product images dynamically based on a requested size parameter. It resizes the original image accordingly and sets cache headers for efficient delivery. Supports 'large', 'medium', 'small', and 'thumbnail' sizes. ```PHP public function serve(): void { $product_id = segment(3, 'int'); $size = segment(4) ?? 'medium'; $product = $this->db->get_where($product_id, 'products'); if ($product === false) { redirect('products/not_found'); } // Check if original image exists if (!$this->file->exists($product->original_image_path)) { redirect('products/image_missing'); } // Load original $this->image->load($product->original_image_path); // Resize based on size parameter switch ($size) { case 'large': $this->image->resize_to_width(1200); break; case 'small': $this->image->resize_to_width(400); break; case 'thumbnail': $this->image->resize_and_crop(200, 200); break; case 'medium': default: $this->image->resize_to_width(800); break; } // Cache for 1 week header('Content-Type: ' . $this->image->get_header()); header('Cache-Control: public, max-age=604800'); $this->image->output(); $this->image->destroy(); } // Usage: yoursite.com/products/serve/123/large ``` -------------------------------- ### Import SQL Files Automatically with Trongate Control Source: https://trongate.io/documentation/trongate_php_framework/module-fundamentals/importing-sql Trongate Control simplifies SQL import by automatically executing SQL files found in a module's directory when the module's URL is visited. This eliminates the need for manual SQL execution or custom installers, streamlining module setup and updates. It also handles version checking for modules and the framework. ```php modules/ forums/ Forums.php Forums_model.php views/ tables.sql data.sql ``` -------------------------------- ### Ordered SQL Files for Sequential Execution Source: https://trongate.io/documentation/trongate_php_framework/module-fundamentals/importing-sql Demonstrates the recommended practice of prefixing SQL files with numbers to ensure sequential execution within a module. ```text modules/shop/ 01_tables.sql 02_categories.sql 03_products.sql ``` -------------------------------- ### User-Friendly Timeout Message Example (PHP & HTML) Source: https://trongate.io/documentation/trongate_mx/events-and-responses/handling-request-timeouts A practical example demonstrating how to display a user-friendly timeout message using `mx-on-timeout` and updating the DOM. This example uses PHP to set up the form attributes and includes a JavaScript function to dynamically insert a warning message into a designated result div when a timeout occurs. ```php 'api/analyze_forum_post', 'mx-timeout' => '60000', 'mx-target' => '#result', 'mx-on-timeout' => 'showTimeoutMessage()' ]; echo form_open('#', $form_attr); echo form_textarea('content'); echo form_submit('submit', 'Analyze'); echo form_close(); ?>
``` -------------------------------- ### MIME Type Verification Example Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/meet-the-image-module Provides an example of the allowed MIME types for image uploads and the error message returned if a file's MIME type does not match. This validation is performed automatically by the `upload()` method. ```php // Automatic validation happens inside upload() $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']; // If MIME doesn't match: "Invalid file type. Only image files are allowed." ``` -------------------------------- ### Testing Constructor Setup (PHP) Source: https://trongate.io/documentation/trongate_php_framework/tips-and-best-practices/mastering-constructors Provides a test method to verify if a controller's constructor is correctly set up. It checks if `$this->module_name` is set, accesses the 'db' module to confirm automatic loading and instantiation, and performs a simple database query. Successful execution indicates the constructor is functioning as expected. ```php public function test() { // Check module_name is set echo "Module name: " . $this->module_name . ""; // Try accessing the db module (loads automatically) echo "Db class: " . get_class($this->db) . ""; // Try a database query $result = $this->db->query('SELECT 1 as test'); echo "Database connected successfully!"; } ``` -------------------------------- ### Validate Project Dates with PHP Callbacks Source: https://trongate.io/documentation/trongate_php_framework/working-with-dates-and-times/validating-date-and-time-data This snippet demonstrates how to validate project start and end dates using PHP. It includes checks for required fields, valid date formats, and custom callback functions to ensure the start date is not in the past and the end date is within a reasonable range relative to the start date. It relies on the Trongate validation library. ```PHP public function submit(): void { $this->validation->set_rules('project_start', 'project start date', 'required|valid_date|callback_reasonable_start_date'); $this->validation->set_rules('project_end', 'project end date', 'required|valid_date|callback_reasonable_timeline'); if ($this->validation->run() === true) { // Process project } else { $this->create(); } } public function callback_reasonable_start_date($start_date): string|true { $today = date('Y-m-d'); $max_future = date('Y-m-d', strtotime('+1 year')); if (strtotime($start_date) < strtotime($today)) { return 'The {label} cannot be in the past.'; } if (strtotime($start_date) > strtotime($max_future)) { return 'The {label} cannot be more than 1 year in the future.'; } return true; } public function callback_reasonable_timeline($end_date): string|true { $start_date = post('project_start', true); if ($start_date === '' || $end_date === '') { return true; } $start = strtotime($start_date); $end = strtotime($end_date); // End must be after start if ($end <= $start) { return 'The {label} must be after the project start date.'; } // Project must be at least 1 week long $min_end = strtotime('+1 week', $start); if ($end < $min_end) { return 'Project must be at least 1 week long.'; } // Project cannot exceed 2 years $max_end = strtotime('+2 years', $start); if ($end > $max_end) { return 'Project duration cannot exceed 2 years.'; } return true; } ``` -------------------------------- ### Extended Pagination Example in HTML Source: https://trongate.io/documentation/trongate_css/utility-classes/pagination Provides an example of an extended pagination component in Trongate CSS, suitable for pages with more content. This snippet shows how to include a larger range of page numbers and navigation links. ```html ``` -------------------------------- ### Image Upload with Configuration Source: https://trongate.io/documentation/trongate_php_framework/image-manipulation/meet-the-image-module Shows how to upload a new image using the `upload()` method with a configuration array. This method handles automatic security validation and can enforce maximum dimensions. ```php $config = [ 'destination' => 'avatars', 'upload_to_module' => true, 'max_width' => 800, 'max_height' => 800 ]; $file_info = $this->image->upload($config); // Image is now in memory, validated, and ready for further processing ```