When managing a table, we often need checkboxes to select multiple items for bulk actions like deleting, updating, or changing categories. This can be easily resolved by creating a Middleware that will prepend a checkbox column to each row.
Create a CheckboxMiddle
:
If the table is being served by a custom adapter, it's best to save shared information in the Cell's
Meta
instance
use Ucscode\HtmlComponent\TableGenerator\TableGenerator;
use Ucscode\HtmlComponent\TableGenerator\Abstraction\AbstractMiddleware;
use Ucscode\HtmlComponent\TableGenerator\Component\Section\Td;
use Ucscode\HtmlComponent\TableGenerator\Component\Section\Tr;
use Ucscode\UssElement\Node\ElementNode;
// Middleware to add checkboxes to each row
class CheckboxMiddleware extends AbstractMiddleware
{
public function process(Table $table): void
{
// Loop through each Tr in the table instance
$this->iterateTrsIn($table, function (Tr $tr) {
// Create a checkbox input
$input = new ElementNode('input', [
'type' => 'checkbox',
// add other attributes
]);
// Create a Td cell and pass the input as data
$cell = new Td($input);
// Prepend the checkbox to the row (tr)
$tr->getCellCollection()->prepend($cell);
});
}
}
Use the CheckboxMiddleware
on the TableGenerator
// Load data (assuming $adapter fetches product data)
$tableGenerator = new TableGenerator($adapter, new CheckboxMiddleware());
// Render the table
echo $tableGenerator->render();
Expected Output
A table where each row has checkbox at the beginning:
☐ | ID | Name | Price |
---|---|---|---|
☐ | 1 | Product A | $10 |
☐ | 2 | Product B | $15 |