In many tables, especially those used for managing products, users, or orders, we often need action buttons for tasks like editing, deleting, or viewing details. This can be efficiently achieved by creating a middleware that appends action buttons to each row.
Create an ActionButtonsMiddleware
If the table is using 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\HtmlComponent\TableGenerator\Contracts\TableSegmentInterface;
use Ucscode\UssElement\Node\ElementNode;
// Middleware to add action buttons to each row
class ActionButtonsMiddleware extends AbstractMiddleware
{
public function process(Table $table): void
{
// Loop through each Tr in the table instance
$this->iterateTrsIn($table, function (Tr $tr, TableSegmentInterface $segment) {
// Check if segment is Thead (or Tfoot)
if ($segment instanceof Thead) {
// Create a Th cell with the text "Actions
$cell = new Th('Actions');
// Append the action cell to the row (tr)
$tr->getCellCollection()->append($cell);
return;
}
// Create action buttons
$editButton = new ElementNode('button', ['class' => 'btn btn-edit']);
$deleteButton = new ElementNode('button', ['class' => 'btn btn-delete']);
// Create text context for each button
$editButton->setInnerHtml('Edit');
$deleteButton->setInnerHtml('Delete');
// Wrap buttons in a container (optional)
$container = new ElementNode('div', ['class' => 'action-buttons']);
$container->appendChild($editButton);
$container->appendChild($deleteButton);
// Create a Td cell and pass the container as data
$cell = new Td($container);
// Append the action cell to the row (tr)
$tr->getCellCollection()->append($cell);
});
}
}
Use the ActionButtonsMiddleware
on the TableGenerator
// Load data (assuming $adapter fetches product data)
$tableGenerator = new TableGenerator($adapter, new ActionButtonsMiddleware());
// Render the table
echo $tableGenerator->render();
Expected Output
A table where each row has "Edit" and "Delete" buttons at the end:
ID | Name | Price | Actions |
---|---|---|---|
1 | Product A | $10 | [Edit] [Delete] |
2 | Product B | $15 | [Edit] [Delete] |