### 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 ```htmlLatest update information.
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 = Modules::run('pagination/show', $pagination_data) ?> ``` -------------------------------- ### 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. ```javascriptThis container has content that will be updated through polling.
```
--------------------------------
### 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