unioil-cms-fe/app/Livewire/Components/Table.php

127 lines
3.6 KiB
PHP

<?php
namespace App\Livewire\Components;
use Livewire\Component;
class Table extends Component
{
// Table Configuration
public $columns = []; // Columns to display
public $rows = []; // Data rows for the table
public $selected = []; // Selected row IDs
public $addRoute = null; // Route for adding new rows (optional)
public $hasAddButton = true;
public $hasDelete = true; // Whether the 'Add' button is shown
public $selectAll = false; // Whether 'Select All' is active
public $hasCheckbox = true; // Whether checkboxes are shown for row selection
public $hasActions = false; // Whether action buttons (like Edit/Delete) are shown
public $isViewPage = false; // Whether the table is for a view page
public $search = ''; // Search query for filtering rows
public $sortField = null; // Column to sort by
public $sortDirection = 'asc'; // Sorting direction (asc or desc)
// Modal Configuration
public $showModal = false; // Whether the modal is visible
public $modalMode = 'view'; // Modal mode: 'view' or 'edit'
public $modalData = []; // Data for the modal
/**
* Initialize the table with given columns and rows
*/
public function mount($columns, $rows, $addRoute = null)
{
$this->columns = $columns;
$this->rows = $rows;
$this->addRoute = $addRoute;
}
/**
* View a row's details in the modal
*/
public function viewRow($id)
{
$this->modalData = collect($this->rows)->firstWhere('id', $id) ?? [];
$this->modalMode = 'view';
$this->showModal = true;
}
/**
* Edit a row's details in the modal
*/
public function editRow($id)
{
$this->modalData = collect($this->rows)->firstWhere('id', $id) ?? [];
$this->modalMode = 'edit';
$this->showModal = true;
}
/**
* Close the modal
*/
public function closeModal()
{
$this->showModal = false;
$this->modalData = [];
}
/**
* Update the selected rows based on search input
*/
public function updatedSearch()
{
$this->selected = [];
}
/**
* Select or deselect all rows
*/
public function selectAllRows()
{
if ($this->selectAll) {
$this->selected = collect($this->rows)->pluck('id')->toArray();
} else {
$this->selected = [];
}
}
/**
* Select or deselect a single row
*/
public function selectRow($rowId)
{
if (in_array($rowId, $this->selected)) {
$this->selected = array_diff($this->selected, [$rowId]);
} else {
$this->selected[] = $rowId;
}
}
/**
* Sort rows by a specific field
*/
public function sortBy($field)
{
if ($this->sortField === $field) {
$this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
} else {
$this->sortField = $field;
$this->sortDirection = 'asc';
}
$this->rows = collect($this->rows)->sortBy(function ($row) {
return $row[$this->sortField] ?? null;
}, SORT_REGULAR, $this->sortDirection === 'desc')->values()->all(); // Use all() to return plain array again
}
/**
* Render the table view
*/
public function render()
{
return view('livewire.components.table', [
'rows' => $this->rows,
]);
}
}