### CodeIgniter 4 Project Setup with Composer and Bash
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Instructions for setting up a new CodeIgniter 4 project using Composer and integrating the CodeIgniter HTMX library. This involves creating a project, installing dependencies, and configuring autoloading.
```bash
# 1. Create new CodeIgniter 4 project
composer create-project codeigniter4/appstarter codeigniterhtmx
cd codeigniterhtmx
# 2. Install CodeIgniter HTMX library
composer require michalsn/codeigniter-htmx
# 3. Download and place demo in app/ThirdParty/htmx-demo/
# 4. Configure namespace in app/Config/Autoload.php:
```
```php
APPPATH,
'Config' => APPPATH . 'Config',
'Michalsn\CodeIgniterHtmxDemo' => APPPATH . 'ThirdParty/htmx-demo/src',
];
```
```bash
# 5. Configure database in app/Config/Database.php
# 6. Run migrations
php spark migrate --all
# 7. Seed demo data (Unix)
php spark db:seed Michalsn\\CodeIgniterHtmxDemo\\Database\\Seeds\\SeedDemo
# 7. Seed demo data (Windows)
php spark db:seed Michalsn\CodeIgniterHtmxDemo\Database\Seeds\SeedDemo
# 8. Access demo at /demo
```
--------------------------------
### Install CodeIgniter 4 with Composer
Source: https://github.com/michalsn/codeigniter-htmx-demo/blob/main/README.md
This command installs the CodeIgniter 4 framework using Composer. It creates a new project directory named 'codeigniterhtmx' and sets up the basic CodeIgniter structure.
```bash
composer create-project codeigniter4/appstarter codeigniterhtmx
cd codeigniterhtmx
```
--------------------------------
### Install CodeIgniter HTMX Library with Composer
Source: https://github.com/michalsn/codeigniter-htmx-demo/blob/main/README.md
This command installs the CodeIgniter HTMX helper library into an existing CodeIgniter project using Composer. It makes the library's functionalities available for use in the application.
```bash
composer require michalsn/codeigniter-htmx
```
--------------------------------
### Books Inline Edit
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Handles inline editing of book records. Accepts GET requests to display the edit form and POST requests to submit updated data with validation.
```APIDOC
## Books Inline Edit
### Description
Provides inline editing functionality for book records with validation and alert feedback using the custom alert helper.
### Method
GET, POST
### Endpoint
/books/edit/{id}
### Parameters
#### Path Parameters
- **id** (integer) - Required - The ID of the book to edit
#### Request Body (for POST)
- **title** (string) - Required - Updated book title (2-100 characters)
- **author** (string) - Required - Updated book author (5-100 characters)
### Request Example (GET)
```
GET /books/edit/1
```
### Request Example (POST)
```
POST /books/edit/1
Content-Type: application/x-www-form-urlencoded
title=Updated+Book+Title&author=Updated+Author+Name
```
### Response
#### Success Response (200)
- **Success**: Returns the updated table row HTML for the book.
- **Validation Error**: Returns the edit form HTML with validation errors and an alert message.
#### Response Example (Success)
```html
1
Updated Book Title
Updated Author Name
...
Book was updated.
```
#### Response Example (Validation Error)
```html
Form validation failed.
```
```
--------------------------------
### CodeIgniter Books Controller - Inline Edit
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
This PHP code snippet from the Books controller implements inline editing for book records. It handles both displaying the edit form via GET requests and processing the submitted data with validation via POST requests. It uses CodeIgniter's validation service and a custom alert helper for feedback. The output is either an editable table row or a display row, suitable for HTMX swaps.
```php
find($id)) {
throw new PageNotFoundException('Incorrect book id.');
}
helper(['form', 'alert']);
$validation = service('validation');
// Show edit form on GET request
if ($this->request->getMethod() !== Method::POST) {
return view('Michalsn\CodeIgniterHtmxDemo\Views\books\table_row_edit', [
'book' => $book, 'validation' => $validation,
]);
}
// Process form submission
$post = $this->request->getPost(['title', 'author']);
$validation->setRules([
'title' => ['required', 'string', 'min_length[2]', 'max_length[100]'],
'author' => ['required', 'string', 'min_length[5]', 'max_length[100]'],
]);
if (! $validation->run($post)) {
return view('Michalsn\CodeIgniterHtmxDemo\Views\books\table_row_edit', [
'book' => $book, 'validation' => $validation,
]).alert('danger', 'Form validation failed.');
}
$model->update($book->id, $post);
$book = (object) array_merge((array) $book, $post);
return view('Michalsn\CodeIgniterHtmxDemo\Views\books\table_row', [
'book' => $book,
]).alert('success', 'Book was updated.');
}
// Frontend HTMX usage:
//
```
--------------------------------
### Migrate Database for CodeIgniter HTMX Demo
Source: https://github.com/michalsn/codeigniter-htmx-demo/blob/main/README.md
This command runs all pending database migrations for the CodeIgniter HTMX Demo project. Ensure your database credentials are correctly set in app/Config/Database.php before execution.
```bash
php spark migrate --all
```
--------------------------------
### TableHelper: Generate Sorting URLs and Indicators (PHP)
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
A PHP utility class for generating sortable table header URLs and visual indicators. It helps manage sorting state and creates links that toggle sort direction. Dependencies include standard PHP string and array functions.
```php
baseURL = $baseURL;
$this->sortColumn = $sortColumn;
$this->sortDirection = $sortDirection;
}
// Generate base URL with current sort params
public function baseURL(): string
{
$queryString = [
'sortColumn' => $this->sortColumn,
'sortDirection' => $this->sortDirection,
];
return $this->baseURL . '?' . http_build_query($queryString);
}
// Generate URL for sorting by column (toggles direction)
public function sortByURL(string $column): string
{
$queryString = [
'sortColumn' => $column,
'sortDirection' => $this->sortColumn === $column
&& $this->sortDirection === 'asc' ? 'desc' : 'asc',
];
return $this->baseURL . '?' . http_build_query($queryString);
}
// Get arrow indicator for current sort
public function getSortIndicator(string $column): string
{
if ($column === $this->sortColumn) {
return $this->sortDirection === 'asc' ? '↑' : '↓';
}
return '';
}
}
// Usage in controller:
$table = new TableHelper('books', $sortColumn, $sortDirection);
// Usage in view:
//
```
--------------------------------
### Configure Autoloading for CodeIgniter HTMX Demo
Source: https://github.com/michalsn/codeigniter-htmx-demo/blob/main/README.md
This snippet shows how to configure the Autoload.php file in CodeIgniter to include the namespace for the CodeIgniter HTMX Demo library. This is essential for the application to recognize and use the demo's classes.
```php
APPPATH, // For custom app namespace
'Config' => APPPATH . 'Config',
'Michalsn\CodeIgniterHtmxDemo' => APPPATH . 'ThirdParty/htmx-demo/src',
];
// ...
```
--------------------------------
### Books List with Search and Pagination
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Retrieves a paginated and searchable list of books. Supports sorting and filtering via query parameters. Returns only the table fragment for HTMX requests.
```APIDOC
## GET /books
### Description
Retrieves a paginated and searchable list of books. Supports sorting and filtering via query parameters. Returns only the table fragment for HTMX requests.
### Method
GET
### Endpoint
/books
### Parameters
#### Query Parameters
- **limit** (integer) - Optional - Items per page (1-10, default: 5)
- **page** (integer) - Optional - Current page number (default: 1)
- **search** (string) - Optional - Search term for title/author
- **sortColumn** (string) - Optional - Column to sort by (id|title|author)
- **sortDirection** (string) - Optional - Sort direction (asc|desc)
### Request Example
```
GET /books?limit=5&page=1&search=CodeIgniter&sortColumn=title&sortDirection=asc
```
### Response
#### Success Response (200)
- **books** (array) - Array of book objects
- **id** (integer) - Book ID
- **title** (string) - Book title
- **author** (string) - Book author
#### Response Example
```json
{
"books": [
{
"id": 1,
"title": "CodeIgniter HTMX Guide",
"author": "John Doe"
}
]
}
```
```
--------------------------------
### CodeIgniter Books Controller - Index/List with Search and Pagination
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
This PHP code snippet from the Books controller handles the display of a paginated and searchable list of books. It accepts query parameters for pagination, search, sorting, and returns only the table fragment for HTMX requests, enabling partial page updates. Dependencies include CodeIgniter's request and model services.
```php
$this->request->getGet('limit') ?? 5,
'page' => $this->request->getGet('page') ?? 1,
'search' => $this->request->getGet('search') ?? '',
'sortColumn' => $this->request->getGet('sortColumn') ?? 'id',
'sortDirection' => $this->request->getGet('sortDirection') ?? 'asc',
];
$model = model(BookModel::class);
$data['books'] = $model
->when($data['search'] !== '', function ($query) use ($data) {
return $query
->like('title', $data['search'], 'both')
->orLike('author', $data['search'], 'both');
})
->orderBy($data['sortColumn'], $data['sortDirection'])
->paginate((int) $data['limit'], 'default', (int) $data['page']);
// Return only table fragment for HTMX requests
if ($this->request->isHtmx() && ! $this->request->isBoosted()) {
return view('Michalsn\CodeIgniterHtmxDemo\Views\books\table', $data);
}
return view('Michalsn\CodeIgniterHtmxDemo\Views\books\index', $data);
}
// Frontend HTMX usage:
//
```
--------------------------------
### CodeIgniter Books Controller: Add and Delete Functionality
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Handles adding new book records and deleting existing ones. It uses CodeIgniter's model and validation services, and returns HTMX-compatible responses for partial page updates. Dependencies include the BookModel and alert/form helpers.
```php
request->getMethod() !== Method::POST) {
return view('Michalsn\CodeIgniterHtmxDemo\Views\books\table_row_add', [
'validation' => $validation,
]);
}
$post = $this->request->getPost(['title', 'author']);
$validation->setRules([
'title' => ['required', 'string', 'min_length[2]', 'max_length[100]'],
'author' => ['required', 'string', 'min_length[5]', 'max_length[100]'],
]);
if (! $validation->run($post)) {
return view('Michalsn\CodeIgniterHtmxDemo\Views\books\table_row_add', [
'validation' => $validation,
]).alert('danger', 'Form validation failed.');
}
if ($id = $model->insert($post)) {
return view('Michalsn\CodeIgniterHtmxDemo\Views\books\table_row', [
'book' => $model->find($id),
]).alert('success', 'The book was added successfully.');
}
return alert('danger', 'Adding a book failed.');
}
// Delete book
public function delete(int $id): string
{
helper('alert');
if (model(BookModel::class)->delete($id)) {
return alert('success', 'The book has been deleted.');
}
return alert('danger', 'Deleting the book failed, or the book does not exist.');
}
// Frontend HTMX usage:
//
```
--------------------------------
### Seed Database for CodeIgniter HTMX Demo (Unix)
Source: https://github.com/michalsn/codeigniter-htmx-demo/blob/main/README.md
This command seeds the database with demo data for the CodeIgniter HTMX Demo project on Unix-like systems. It uses the specified SeedDemo class to populate the database.
```bash
php spark db:seed Michalsn\CodeIgniterHtmxDemo\Database\Seeds\SeedDemo
```
--------------------------------
### Tasks Model - Custom Query Methods
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Provides custom methods for filtering and batch operations on tasks.
```APIDOC
## TaskModel Methods
### Description
Custom methods for filtering and batch operations on tasks.
### Methods
#### `getAll(?string $type = null): array`
##### Description
Get all tasks, optionally filtered by type.
##### Parameters
- **type** (string) - Optional - The type of task to filter by (e.g., 'active', 'completed').
##### Returns
An array of task objects.
#### `countByType(string $type): int`
##### Description
Count tasks by type (active or completed).
##### Parameters
- **type** (string) - Required - The type of task to count (e.g., 'active', 'completed').
##### Returns
An integer representing the count of tasks of the specified type.
#### `deleteCompleted(): int`
##### Description
Delete all tasks with the type 'completed'.
##### Returns
An integer representing the number of deleted tasks.
```
--------------------------------
### Toast Notification Helper Function in CodeIgniter
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Provides a helper function `alert()` to generate HTMX out-of-band (OOB) swap notifications for toast messages. This function creates a dismissible toast element that is automatically appended to a specified container. It supports different alert types like 'success', 'danger', 'warning', and 'info'.
```php
CodeIgniter HTMX Demo
%s
', $type, $message);
}
// Usage in controllers:
helper('alert');
return view('books/table_row', ['book' => $book]).alert('success', 'Book was updated.');
// Types: 'success', 'danger', 'warning', 'info'
// Required HTML container in layout:
//
```
--------------------------------
### Tasks Management API
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Endpoints for managing a todo list, including adding, toggling, filtering, and deleting tasks. Supports HTMX for dynamic UI updates and client-side event triggering.
```APIDOC
## GET /tasks
### Description
Lists all tasks. If the request is an HTMX request, it returns a fragment of the task list.
### Method
GET
### Endpoint
/tasks
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns the full task list view or a fragment for HTMX requests.
#### Response Example
```html
```
## GET /tasks/active
### Description
Lists only the active tasks.
### Method
GET
### Endpoint
/tasks/active
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns the HTML for the active task list.
#### Response Example
```html
```
## GET /tasks/completed
### Description
Lists only the completed tasks.
### Method
GET
### Endpoint
/tasks/completed
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns the HTML for the completed task list.
#### Response Example
```html
```
## POST /tasks
### Description
Adds a new task to the todo list. Triggers a `taskAdded` client event upon successful addition.
### Method
POST
### Endpoint
/tasks
### Parameters
#### Query Parameters
None
#### Request Body
- **name** (string) - Required - The name of the task.
### Request Example
```json
{
"name": "Buy groceries"
}
```
### Response
#### Success Response (200)
Returns the HTML for the newly added task and a success alert.
#### Response Example
```html
New task was added successfully.
```
## PUT /tasks/toggle/{id}
### Description
Toggles the status of a single task (active to completed, or vice versa). Triggers `taskToggled` and `checkIfThereAreTasks` client events.
### Method
PUT
### Endpoint
/tasks/toggle/{id}
### Parameters
#### Path Parameters
- **id** (int) - Required - The ID of the task to toggle.
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns the updated HTML for the task and a success alert.
#### Response Example
```html
Task updated.
```
## PUT /tasks/toggle-all
### Description
Toggles the status of all tasks.
### Method
PUT
### Endpoint
/tasks/toggle-all
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns a success message or updated task list.
#### Response Example
```html
```
## DELETE /tasks/{id}
### Description
Deletes a specific task by its ID.
### Method
DELETE
### Endpoint
/tasks/{id}
### Parameters
#### Path Parameters
- **id** (int) - Required - The ID of the task to delete.
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns a success message indicating the task has been deleted.
#### Response Example
```html
```
## DELETE /tasks/clear-completed
### Description
Clears all completed tasks from the list.
### Method
DELETE
### Endpoint
/tasks/clear-completed
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns a success message indicating completed tasks have been cleared.
#### Response Example
```html
```
## GET /tasks/summary
### Description
Retrieves a summary of task counts (active and completed).
### Method
GET
### Endpoint
/tasks/summary
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns a JSON object with counts of active and completed tasks.
#### Response Example
```json
{
"active": 5,
"completed": 10
}
```
```
--------------------------------
### Paragraphs Controller - Sortable Content with Modal Edit
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Handles listing, editing, and reordering of paragraphs using HTMX and modal views.
```APIDOC
## Paragraphs Controller API
### Description
Endpoints for managing sortable paragraphs with modal-based editing and HTMX interactions.
### Endpoints
#### GET /paragraphs
##### Description
Retrieves a list of all paragraphs, ordered by their sort order. Can be requested via HTMX for partial updates.
##### Method
GET
##### Endpoint
`/paragraphs`
##### Query Parameters
None
##### Request Body
None
##### Response
#### Success Response (200)
- **paragraphs** (array) - An array of paragraph objects, each with an `id`, `title`, `body`, and `sort` field.
#### GET /paragraphs/edit/{id}
##### Description
Retrieves the content for a modal to edit a specific paragraph.
##### Method
GET
##### Endpoint
`/paragraphs/edit/{id}`
##### Path Parameters
- **id** (int) - Required - The ID of the paragraph to edit.
##### Request Body
None
##### Response
#### Success Response (200)
- HTML content for the edit modal.
#### POST /paragraphs/edit/{id}
##### Description
Submits the updated content for a paragraph. Handles validation and returns either the updated list or validation errors within the modal.
##### Method
POST
##### Endpoint
`/paragraphs/edit/{id}`
##### Path Parameters
- **id** (int) - Required - The ID of the paragraph to update.
##### Request Body
- **title** (string) - Required - The new title for the paragraph.
- **body** (string) - Required - The new body content for the paragraph.
##### Response
#### Success Response (200)
- If validation passes, returns the updated paragraph list and a success alert.
#### Error Response (400)
- If validation fails, returns the modal fields with validation errors and an error alert.
#### POST /paragraphs/reorder
##### Description
Reorders paragraphs based on the provided array of IDs. This endpoint is typically triggered by HTMX after a drag-and-drop operation.
##### Method
POST
##### Endpoint
`/paragraphs/reorder`
##### Query Parameters
None
##### Request Body
- **ids** (array) - Required - An array of paragraph IDs in the desired new order.
##### Response
#### Success Response (200)
- Returns the updated paragraph list and a success alert indicating the order has been changed.
```
--------------------------------
### Paginated Table Widget with Search and Sort in CodeIgniter
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Implements a self-contained paginated table widget using CodeIgniter's view cells. It supports searching, sorting by specified columns, and pagination. The cell takes parameters like page, limit, search query, sort column, and sort direction. It relies on the BookModel for data retrieval and CodeIgniter's Pager for pagination.
```php
sortColumn, $this->validSortColumns)) {
throw new InvalidArgumentException('Sort column is out of the range.');
}
helper('form');
$model = model(BookModel::class);
$this->books = $model
->when($this->search !== '', function ($query) {
return $query
->like('title', $this->search, 'both')
->orLike('author', $this->search, 'both');
})
->orderBy($this->sortColumn, $this->sortDirection)
->paginate((int) $this->limit, 'default', (int) $this->page);
$this->pager = $model->pager->setPath($this->baseURL);
}
// Generate sort URL with toggled direction
protected function sortByURL(string $column): string
{
$queryString = [
'sortColumn' => $column,
'sortDirection' => $this->sortColumn === $column
&& $this->sortDirection === 'asc' ? 'desc' : 'asc',
];
return $this->baseURL . '?' . http_build_query($queryString);
}
// Get sort indicator arrow
protected function getSortIndicator(string $column): string
{
if ($column === $this->sortColumn) {
return $this->sortDirection === 'asc' ? '↑' : '↓';
}
return '';
}
}
// Route definition:
$routes->get('table-advanced', static function () {
return view_cell('Michalsn\CodeIgniterHtmxDemo\Cells\TableAdvanced\TableAdvancedCell',
service('request')->getGet());
});
```
--------------------------------
### Paragraphs Controller: Sortable Content and Modal Editing in CodeIgniter with HTMX
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
This controller demonstrates how to implement sortable content using drag-and-drop functionality and modal-based editing with view fragments in CodeIgniter. It handles listing paragraphs, fetching edit modal content, submitting edits, and reordering paragraphs via HTMX requests. The controller utilizes helper functions for forms and alerts, and services for validation.
```php
$model->orderBy('sort', 'asc')->findAll(),
];
if ($this->request->isHtmx() && ! $this->request->isBoosted()) {
return view_fragment('Michalsn\CodeIgniterHtmxDemo\Views\paragraphs\index', 'paragraphs', $data);
}
return view('Michalsn\CodeIgniterHtmxDemo\Views\paragraphs\index', $data);
}
// Modal edit with fragment response
public function edit(int $id): string
{
$model = model(ParagraphModel::class);
if (! $paragraph = $model->find($id)) {
throw new PageNotFoundException('Incorrect paragraph id.');
}
helper(['form', 'alert']);
$validation = service('validation');
if ($this->request->getMethod() !== Method::POST) {
return view('Michalsn\CodeIgniterHtmxDemo\Views\paragraphs\edit', [
'paragraph' => $paragraph, 'validation' => $validation,
]);
}
$post = $this->request->getPost(['title', 'body']);
$validation->setRules([
'title' => ['required', 'string', 'min_length[5]', 'max_length[64]'],
'body' => ['required', 'string', 'min_length[20]', 'max_length[255]'],
]);
if (! $validation->run($post)) {
// Retarget to modal fields only on validation failure
$this->response->setReswap('innerHTML')->setRetarget('#modal-fields');
return view_fragment('Michalsn\CodeIgniterHtmxDemo\Views\paragraphs\edit', 'fields', [
'paragraph' => $paragraph, 'validation' => $validation,
]).alert('danger', 'Form validation failed.');
}
$model->update($paragraph->id, $post);
$this->response->triggerClientEvent('closeModal');
return $this->index().alert('success', 'Paragraph was updated.');
}
// Drag-and-drop reorder handler
public function reorder(): string
{
$ids = array_map('intval', $this->request->getPost('ids') ?? []);
if (empty($ids)) {
throw new PageNotFoundException('Missing paragraph IDs.');
}
helper('alert');
$model = model(ParagraphModel::class);
// Build batch update data with new sort order
$data = [];
foreach ($ids as $key => $id) {
$data[] = ['id' => $id, 'sort' => $key + 1];
}
$model->updateBatch($data, 'id');
return $this->index().alert('success', 'The order of paragraphs has been changed.');
}
// Frontend HTMX usage (with Sortable.js):
//
//
Paragraph 1
//
Paragraph 2
//
```
--------------------------------
### Books Management API
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Endpoints for adding and deleting book records. These endpoints are designed to work with HTMX for dynamic updates without full page reloads.
```APIDOC
## GET /books/add
### Description
Displays the form to add a new book.
### Method
GET
### Endpoint
/books/add
### Parameters
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns the HTML for the add book form.
#### Response Example
```html
```
## POST /books/add
### Description
Submits a new book record. Performs validation and adds the book to the database.
### Method
POST
### Endpoint
/books/add
### Parameters
#### Query Parameters
None
#### Request Body
- **title** (string) - Required - The title of the book.
- **author** (string) - Required - The author of the book.
### Request Example
```json
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
}
```
### Response
#### Success Response (200)
Returns the HTML for the newly added book row and a success alert.
#### Response Example
```html
The book was added successfully.
```
## DELETE /books/delete/{id}
### Description
Deletes an existing book record by its ID.
### Method
DELETE
### Endpoint
/books/delete/{id}
### Parameters
#### Path Parameters
- **id** (int) - Required - The ID of the book to delete.
#### Query Parameters
None
#### Request Body
None
### Response
#### Success Response (200)
Returns a success alert indicating the book has been deleted.
#### Response Example
```html
The book has been deleted.
```
```
--------------------------------
### CodeIgniter Tasks Controller: Todo List with HTMX
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Implements a complete todo list with add, toggle, filter by status, and event-driven updates using HTMX client events. It leverages CodeIgniter's model, validation, and response triggering capabilities. Supports filtering by active or completed tasks.
```php
$type,
'tasks' => $model->getAll($type),
'countActive' => $model->countByType('active'),
'countCompleted' => $model->countByType('completed'),
];
// Return fragment for HTMX requests using view_fragment
if ($this->request->isHtmx() && ! $this->request->isBoosted()) {
return view_fragment('Michalsn\CodeIgniterHtmxDemo\Views\tasks\index', 'tasks', $data);
}
return view('Michalsn\CodeIgniterHtmxDemo\Views\tasks\index', $data);
}
// Add task with event trigger
public function add(): string
{
$model = model(TaskModel::class);
helper(['form', 'alert']);
$validation = service('validation');
$post = $this->request->getPost(['name']);
$validation->setRules([
'name' => ['required', 'string', 'min_length[5]', 'max_length[64]'],
]);
if (! $validation->run($post)) {
return alert('danger', $validation->getError('name'));
}
if ($id = $model->insert($post)) {
// Trigger client-side event for other components
$this->response->triggerClientEvent('taskAdded');
return view('Michalsn\CodeIgniterHtmxDemo\Views\tasks\task', [
'task' => $model->find($id),
]).alert('success', 'New task was added successfully.');
}
return alert('danger', 'Adding a task failed.');
}
// Toggle single task
public function toggle(int $id)
{
helper('alert');
$model = model(TaskModel::class);
if (! $task = $model->find($id)) {
return alert('danger', 'Incorrect task ID.');
}
$task->type = $task->type === 'active' ? 'completed' : 'active';
$model->update($task->id, ['type' => $task->type]);
// Trigger multiple events
$this->response->triggerClientEvent('taskToggled');
$this->response->triggerClientEvent('checkIfThereAreTasks', '', 'swap');
return view('Michalsn\CodeIgniterHtmxDemo\Views\tasks\task', [
'task' => $task,
]).alert('success', 'Task updated.');
}
// Frontend HTMX usage:
//
//
```
--------------------------------
### Secure Counter Cell with Signed URLs in CodeIgniter
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
An advanced counter cell that enhances security by using signed URLs to prevent tampering with query parameters. It requires the 'michalsn/codeigniter-signed-url' library. The `mount` method verifies the signature on incoming requests.
```php
getGet() !== []) {
try {
service('signedurl')->verify(service('incomingrequest'));
} catch (SignedUrlException $e) {
throw $e;
}
}
}
public function increment()
{
$this->count += $this->step;
return $this->render();
}
public function decrement()
{
$this->count -= $this->step;
return $this->render();
}
// Generate query string for signed URL
public function getQueryString()
{
return http_build_query([
'count' => $this->count,
'step' => $this->step,
]);
}
}
// Usage in view with signed URL:
//
```
--------------------------------
### TaskModel: Custom Query Methods in CodeIgniter
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
The TaskModel extends CodeIgniter's base Model class to provide custom methods for retrieving, counting, and deleting tasks. It includes functionality for filtering tasks by type, counting tasks of a specific type, and deleting all completed tasks. This model is designed to streamline data operations within the application.
```php
where('type', $type);
}
return $this->findAll();
}
// Count tasks by type (active or completed)
public function countByType(string $type): int
{
return $this->where('type', $type)->countAllResults();
}
// Delete all completed tasks
public function deleteCompleted(): int
{
return $this->where('type', 'completed')->delete();
}
}
// Usage in controller:
// $tasks = model(TaskModel::class)->getAll('active');
// $activeCount = model(TaskModel::class)->countByType('active');
// model(TaskModel::class)->deleteCompleted();
```
--------------------------------
### Stateless Counter Cell with HTMX in CodeIgniter
Source: https://context7.com/michalsn/codeigniter-htmx-demo/llms.txt
Implements a simple counter widget using CodeIgniter's view cells and HTMX. This component is stateless, meaning it doesn't maintain server-side state. It handles increment and decrement actions via HTMX requests.
```php
count++;
return $this->render();
}
public function decrement()
{
$this->count--;
return $this->render();
}
}
// Route definition:
$routes->group('cells/counter', static function ($routes) {
$routes->get('increment', static function () {
return view_cell('Michalsn\CodeIgniterHtmxDemo\Cells\Counter\CounterCell::increment',
service('request')->getGet());
});
$routes->get('decrement', static function () {
return view_cell('Michalsn\CodeIgniterHtmxDemo\Cells\Counter\CounterCell::decrement',
service('request')->getGet());
});
});
// Cell view (counter.php):
//
//
//
//
//
//
//
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.