6. Order lines
You will edit an order that has any number of lines, using a fieldset repeated by a Collection. People can add and remove lines without JavaScript.
Try it: Mezzio ยท laminas-mvc
Assumes you have done chapter 0 and chapter 4.
<?php
declare(strict_types=1);
namespace App\Forms\Order;
use App\Forms\Csrf\AbstractCsrfProtectedForm;
use Laminas\Filter\StringTrim;
use Laminas\Form\Element\Collection;
use Laminas\Form\Element\Hidden;
use Laminas\Form\Element\Submit;
use Laminas\Form\Element\Text;
use Laminas\Hydrator\ReflectionHydrator;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\Between;
use Laminas\Validator\NotEmpty;
use Laminas\Validator\StringLength;
use LogicException;
use Override;
use Traversable;
use function array_key_exists;
use function count;
use function iterator_to_array;
use function sprintf;
/**
* Edits an Order and its lines. Bind one before validating
*
* Lines are added and removed with submit buttons, so no JavaScript is needed. After setData(), ask
* linesWereChanged(): if it is true, show the form again instead of validating it.
*
* @api
*
* @extends AbstractCsrfProtectedForm<Order>
*/
final class OrderForm extends AbstractCsrfProtectedForm implements InputFilterProviderInterface
{
public const int MAX_LINES = 20;
private bool $linesChanged = false;
/** @var positive-int|null */
private ?int $removedLine = null;
#[Override]
public function getInputFilterSpecification(): array
{
return [
'reference' => [
'required' => true,
'filters' => [['name' => StringTrim::class]],
'validators' => [
[
'name' => NotEmpty::class,
'break_chain_on_failure' => true,
'options' => ['messages' => [NotEmpty::IS_EMPTY => 'Enter an order reference']],
],
[
'name' => StringLength::class,
'options' => [
'max' => 30,
'messages' => [StringLength::TOO_LONG => 'The reference must be 30 characters or fewer'],
],
],
],
],
'line_count' => [
'required' => true,
'validators' => [['name' => Between::class, 'options' => ['min' => 0, 'max' => self::MAX_LINES]]],
'error_message' => sprintf('An order can have up to %d lines', self::MAX_LINES),
],
];
}
#[Override]
public function init(): void
{
parent::init();
$this->setHydrator(new ReflectionHydrator());
$this->add([
'name' => 'reference',
'type' => Text::class,
'options' => ['label' => 'Order reference'],
'attributes' => ['id' => 'reference', 'required' => true, 'maxlength' => 30],
]);
$this->add([
'name' => 'lines',
'type' => Collection::class,
'options' => [
'count' => 1,
'allow_add' => true,
'allow_remove' => true,
// A line is only its fields, so build new objects instead of reusing them by position
'create_new_objects' => true,
'target_element' => ['type' => LineFieldset::class],
],
]);
// Never shown. setData() fills it in, so that too many lines are reported like any other error
$this->add([
'name' => 'line_count',
'type' => Hidden::class,
]);
$this->add([
'name' => 'add_line',
'type' => Submit::class,
'attributes' => [
'id' => 'add_line',
'value' => 'Add another line',
'class' => 'secondary',
'formnovalidate' => 'formnovalidate',
],
]);
$this->add([
'name' => 'save',
'type' => Submit::class,
'attributes' => ['value' => 'Save order'],
]);
}
/** @return list<LineFieldset> */
public function lines(): array
{
$collection = $this->get('lines');
$lines = [];
foreach ($collection instanceof Collection ? $collection->getFieldsets() : [] as $line) {
if (! $line instanceof LineFieldset) {
continue;
}
$lines[] = $line;
}
return $lines;
}
/** True when the last data asked to add or remove a line, rather than to save */
public function linesWereChanged(): bool
{
return $this->linesChanged;
}
#[Override]
public function prepare(): static
{
parent::prepare();
foreach ($this->lines() as $index => $line) {
$line->number($index + 1);
}
return $this;
}
/**
* The number of the line the last data removed, so the page can say so
*
* Show the message in an element with the id "line-removed". It describes the "Add another line" button.
*
* @return positive-int|null
*/
public function removedLine(): ?int
{
return $this->removedLine;
}
/**
* @param iterable<mixed, mixed> $data
* @throws LogicException If there is no line to move to.
*/
#[Override]
public function setData(iterable $data): static
{
$data = $data instanceof Traversable ? iterator_to_array($data) : $data;
$add = array_key_exists('add_line', $data);
$lines = SubmittedLines::from($data['lines'] ?? null, self::MAX_LINES);
if ($add) {
$lines = $lines->withBlankRow(self::MAX_LINES);
}
$this->linesChanged = $add || null !== $lines->removed;
$this->removedLine = $lines->removed;
// The buttons keep their own labels
unset($data['add_line'], $data['save']);
parent::setData([
...$data,
'lines' => $lines->rows,
'line_count' => $lines->submitted,
]);
// Keeps keyboard and screen reader users where they were working
if ($add) {
$this->focusLastLine();
}
if (null !== $lines->removed && ! $add) {
// Describes the focused button, as a live region already on the page may not be announced
$this->get('add_line')->setAttribute('autofocus', true)->setAttribute('aria-describedby', 'line-removed');
}
return $this;
}
/** @throws LogicException If there is no line to move to. */
private function focusLastLine(): void
{
$lines = $this->lines();
$last = $lines[count($lines) - 1] ?? throw new LogicException('The order has no lines');
$last->get('description')->setAttribute('autofocus', true);
}
}
The fieldset that is repeated:
<?php
declare(strict_types=1);
namespace App\Forms\Order;
use Laminas\Filter\StringTrim;
use Laminas\Form\Element\Button;
use Laminas\Form\Element\Text;
use Laminas\Form\Fieldset;
use Laminas\Hydrator\ReflectionHydrator;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\NotEmpty;
use Laminas\Validator\Regex;
use Laminas\Validator\StringLength;
use Override;
/**
* One line of an order
*
* @api
*/
final class LineFieldset extends Fieldset implements InputFilterProviderInterface
{
private const string QUANTITY = 'Enter a quantity as a whole number from 1 to 9999';
private const string PRICE = 'Enter a unit price as an amount, such as 12.50';
#[Override]
public function getInputFilterSpecification(): array
{
return [
'description' => [
'required' => true,
'filters' => [['name' => StringTrim::class]],
'validators' => [
[
'name' => NotEmpty::class,
'break_chain_on_failure' => true,
'options' => ['messages' => [NotEmpty::IS_EMPTY => 'Enter a description']],
],
[
'name' => StringLength::class,
'options' => [
'max' => 100,
'messages' => [StringLength::TOO_LONG => 'The description must be 100 characters or fewer'],
],
],
],
],
'quantity' => $this->matching('/\A[1-9][0-9]{0,3}\z/', self::QUANTITY),
'price' => $this->matching('/\A(0|[1-9][0-9]{0,5})(\.[0-9]{1,2})?\z/', self::PRICE),
'remove' => ['required' => false],
];
}
#[Override]
public function init(): void
{
$this->setHydrator(new ReflectionHydrator());
$this->setObject(new Line());
$this->add([
'name' => 'description',
'type' => Text::class,
'options' => ['label' => 'Description'],
'attributes' => ['required' => true, 'maxlength' => 100],
]);
// Text with a numeric keyboard: number inputs change value on scrolling, and hide what was mistyped
$this->add([
'name' => 'quantity',
'type' => Text::class,
'options' => ['label' => 'Quantity'],
'attributes' => ['required' => true, 'inputmode' => 'numeric', 'maxlength' => 4],
]);
$this->add([
'name' => 'price',
'type' => Text::class,
'options' => ['label' => 'Unit price', 'hint' => 'For example, 12.50.'],
'attributes' => ['required' => true, 'inputmode' => 'decimal', 'maxlength' => 9],
]);
$this->add([
'name' => 'remove',
'type' => Button::class,
'options' => ['label' => 'Remove line'],
'attributes' => [
'type' => 'submit',
'value' => '1',
'class' => 'secondary',
'formnovalidate' => 'formnovalidate',
],
]);
}
/**
* Gives this line its visible number, and ids that no other line has
*
* @param positive-int $number
*/
public function number(int $number): void
{
$this->setLabel("Line {$number}");
foreach (['description', 'quantity', 'price'] as $name) {
$this->get($name)->setAttribute('id', "line-{$number}-{$name}");
}
$this->get('remove')->setLabel("Remove line {$number}");
}
/**
* @param non-empty-string $pattern
* @return array{
* required: true,
* filters: list<array{name: class-string<StringTrim>}>,
* validators: list<array{name: class-string<Regex>, options: array{pattern: non-empty-string}}>,
* error_message: string
* }
*/
private function matching(string $pattern, string $message): array
{
return [
'required' => true,
'filters' => [['name' => StringTrim::class]],
'validators' => [['name' => Regex::class, 'options' => ['pattern' => $pattern]]],
'error_message' => $message,
];
}
}
A request can hold anything, so the submitted lines are tidied first:
<?php
declare(strict_types=1);
namespace App\Forms\Order;
use function array_key_exists;
use function array_slice;
use function count;
use function is_array;
use function is_string;
/**
* The order lines as they were sent, made safe to give to the form
*
* A request can hold anything. Whatever is not a line is dropped, whatever is not text becomes an
* empty string, lines marked for removal are left out, and there is always at least one line.
*/
final readonly class SubmittedLines
{
/**
* @param non-empty-list<array{description: string, quantity: string, price: string}> $rows
* @param int<0, max> $submitted How many lines were sent, which may be more than were kept
* @param positive-int|null $removed The number of the first line left out for removal, counting from one
*/
private function __construct(
public array $rows,
public int $submitted,
public ?int $removed,
) {}
/** @param positive-int $max */
public static function from(mixed $lines, int $max): self
{
$rows = [];
$removed = null;
/** @var mixed $line */
foreach (is_array($lines) ? $lines : [] as $line) {
if (! is_array($line)) {
continue;
}
if (array_key_exists('remove', $line)) {
$removed ??= count($rows) + 1;
continue;
}
$rows[] = [
'description' => self::text($line['description'] ?? null),
'quantity' => self::text($line['quantity'] ?? null),
'price' => self::text($line['price'] ?? null),
];
}
$kept = array_slice($rows, offset: 0, length: $max);
return new self([] === $kept ? [self::blank()] : $kept, count($rows), $removed);
}
/** @return array{description: string, quantity: string, price: string} */
private static function blank(): array
{
return ['description' => '', 'quantity' => '1', 'price' => ''];
}
private static function text(mixed $value): string
{
return is_string($value) ? $value : '';
}
/**
* Adds an empty line, unless there are already $max
*
* @param positive-int $max
*/
public function withBlankRow(int $max): self
{
if ($max <= count($this->rows)) {
return $this;
}
$rows = [...$this->rows, self::blank()];
return new self($rows, count($rows), $this->removed);
}
}
The objects the form edits:
<?php
declare(strict_types=1);
namespace App\Forms\Order;
use function array_map;
use function array_sum;
use function intdiv;
use function sprintf;
final class Order
{
/** @param list<Line> $lines */
public function __construct(
public string $reference = '',
public array $lines = [],
) {}
/** The sum of all lines, with two decimal places */
public function total(): string
{
$cents = array_sum(array_map(static fn(Line $line): int => $line->totalInCents(), $this->lines));
return sprintf('%d.%02d', intdiv($cents, num2: 100), $cents % 100);
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Order;
use function explode;
use function str_pad;
final class Line
{
/** @param string $price Unit price with up to two decimal places, such as "12.50" */
public function __construct(
public string $description = '',
public int $quantity = 1,
public string $price = '',
) {}
/** Counted in cents, because floating point numbers cannot hold money exactly */
public function totalInCents(): int
{
[$units, $fraction] = [...explode('.', $this->price), ''];
return $this->quantity * (((int) $units * 100) + (int) str_pad($fraction, length: 2, pad_string: '0'));
}
}
The handler or controller asks for the order through a one-method interface:
<?php
declare(strict_types=1);
namespace App\Forms\Order;
/** @api */
interface OrderProviderInterface
{
public function current(): Order;
}
<?php
declare(strict_types=1);
namespace App\Forms\Order;
use Override;
/** A made-up order. Load yours from storage instead */
final class DemoOrderProvider implements OrderProviderInterface
{
#[Override]
public function current(): Order
{
return new Order('PO-1001', [
new Line('Notebooks', 10, '3.50'),
new Line('Desk lamp', 1, '26.00'),
]);
}
}
The form needs no factory. FormElementManager creates it, and the fieldset, and calls init().
Mezzio
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Forms\Order\OrderProviderInterface;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;
/** @api */
final class OrderHandlerFactory
{
public function __invoke(ContainerInterface $container): OrderHandler
{
return new OrderHandler(
$container->get(FormElementManager::class),
$container->get(TemplateRendererInterface::class),
$container->get(OrderProviderInterface::class),
);
}
}
<?php
declare(strict_types=1);
namespace App;
use App\Forms\Order\DemoOrderProvider;
use App\Forms\Order\OrderProviderInterface;
use App\Handler\OrderHandler;
use App\Handler\OrderHandlerFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;
/** @api */
final class OrderConfigProvider
{
/** @return array<string, mixed> */
public function __invoke(): array
{
return [
'dependencies' => [
'aliases' => [
OrderProviderInterface::class => DemoOrderProvider::class,
],
'factories' => [
DemoOrderProvider::class => InvokableFactory::class,
OrderHandler::class => OrderHandlerFactory::class,
],
],
];
}
}
Add the provider to config/config.php, and register the route:
<?php
declare(strict_types=1);
use App\Handler\OrderHandler;
use Mezzio\Application;
return static function (Application $app): void {
$app->route('/order', OrderHandler::class, ['GET', 'POST'], 'order');
};
laminas-mvc
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Order\OrderProviderInterface;
use Laminas\Form\FormElementManager;
use Psr\Container\ContainerInterface;
/** @api */
final class OrderControllerFactory
{
public function __invoke(ContainerInterface $container): OrderController
{
return new OrderController(
$container->get(FormElementManager::class),
$container->get(CsrfGuardInterface::class),
$container->get(OrderProviderInterface::class),
);
}
}
Merge this file into your module configuration, as Module does in chapter 0:
<?php
declare(strict_types=1);
namespace Application;
use App\Forms\Order\DemoOrderProvider;
use App\Forms\Order\OrderProviderInterface;
use Laminas\Router\Http\Literal;
use Laminas\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'order' => [
'type' => Literal::class,
'options' => [
'route' => '/order',
'defaults' => ['controller' => Controller\OrderController::class, 'action' => 'form'],
],
],
],
],
'controllers' => [
'factories' => [
Controller\OrderController::class => Controller\OrderControllerFactory::class,
],
],
'service_manager' => [
'aliases' => [
OrderProviderInterface::class => DemoOrderProvider::class,
],
'factories' => [
DemoOrderProvider::class => InvokableFactory::class,
],
],
'view_manager' => [
'template_map' => [
'forms::order' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/order.phtml',
],
],
];
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var App\Forms\Order\OrderForm $form
* @var string|null $status
*/
$form->prepare();
$this->headTitle($form->getMessages() === [] ? 'Edit order' : 'Error: Edit order', 'SET');
$lines = $form->lines();
?>
<?= $this->partial('forms::error-summary', ['form' => $form]) ?>
<h1>Edit order</h1>
<?php if ($status !== null): ?>
<p role="status" tabindex="-1" autofocus><?= $this->escapeHtml($status) ?></p>
<?php endif; ?>
<p>All fields are required.</p>
<?= $this->form()->openTag($form) ?>
<?php /* Pressing Enter uses the first button in a form, which must not be one that removes a line */ ?>
<input type="submit" name="save" value="Save order" class="visually-hidden" tabindex="-1" aria-hidden="true">
<?= $this->formElement($form->get('csrf')) ?>
<?= $this->partial('forms::field', ['element' => $form->get('reference')]) ?>
<?php foreach ($lines as $line): ?>
<fieldset class="line">
<legend><?= $this->escapeHtml($line->getLabel()) ?></legend>
<?= $this->partial('forms::field', ['element' => $line->get('description')]) ?>
<?= $this->partial('forms::field', ['element' => $line->get('quantity')]) ?>
<?= $this->partial('forms::field', ['element' => $line->get('price')]) ?>
<?php if (count($lines) > 1): ?>
<?= $this->formElement($line->get('remove')) ?>
<?php endif; ?>
</fieldset>
<?php endforeach; ?>
<?php if ($form->removedLine() !== null): ?>
<p id="line-removed">Line <?= $form->removedLine() ?> was removed. Any lines after it have moved up.</p>
<?php endif; ?>
<?php if (count($lines) < $form::MAX_LINES): ?>
<p><?= $this->formElement($form->get('add_line')) ?></p>
<?php endif; ?>
<?= $this->formElement($form->get('save')) ?>
<?= $this->form()->closeTag() ?>
The error summary from chapter 0 follows each fieldset down to its fields, and puts the fieldset's label in front of the message:
<?php
declare(strict_types=1);
use Laminas\Form\FieldsetInterface;
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var Laminas\Form\FormInterface $form
*/
if ($form->getMessages() === []) {
return;
}
// Messages are nested the way the fields are, so follow each fieldset down to its elements
$errors = [];
$collect = static function (FieldsetInterface $fieldset, array $messages, string $context) use (&$collect, &$errors): void {
foreach ($messages as $name => $found) {
$element = $fieldset->get((string) $name);
if ($element instanceof FieldsetInterface) {
$label = (string) $element->getLabel();
$collect($element, $found, $label === '' ? $context : $context . $label . ': ');
continue;
}
foreach ($found as $message) {
$errors[] = [$element, $context . $message];
}
}
};
$collect($form, $form->getMessages(), '');
?>
<div class="error-summary" role="alert" tabindex="-1" autofocus aria-labelledby="error-summary-title">
<h2 id="error-summary-title">There is a problem</h2>
<ul>
<?php foreach ($errors as [$element, $message]): ?>
<li>
<?php if ($element->getAttribute('type') === 'hidden'): ?>
<?= $this->escapeHtml($message) ?>
<?php else: ?>
<a href="#<?= $this->escapeHtmlAttr($element->getAttribute('id')) ?>"><?= $this->escapeHtml($message) ?></a>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Csrf\MezzioCsrfGuard;
use App\Forms\Order\Order;
use App\Forms\Order\OrderForm;
use App\Forms\Order\OrderProviderInterface;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Form\FormElementManager;
use Mezzio\Csrf\CsrfGuardInterface;
use Mezzio\Csrf\CsrfMiddleware;
use Mezzio\Flash\FlashMessageMiddleware;
use Mezzio\Flash\FlashMessagesInterface;
use Mezzio\Template\TemplateRendererInterface;
use Override;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/** @api */
final readonly class OrderHandler implements RequestHandlerInterface
{
public function __construct(
private FormElementManager $forms,
private TemplateRendererInterface $renderer,
private OrderProviderInterface $orders,
) {}
#[Override]
public function handle(ServerRequestInterface $request): ResponseInterface
{
/** @var CsrfGuardInterface $guard */
$guard = $request->getAttribute(CsrfMiddleware::GUARD_ATTRIBUTE);
/** @var FlashMessagesInterface $flash */
$flash = $request->getAttribute(FlashMessageMiddleware::FLASH_ATTRIBUTE);
$form = $this->forms->get(OrderForm::class);
$form->setCsrfGuard(new MezzioCsrfGuard($guard));
// Fills the fields now, and receives the new values when they are valid
$form->bind($this->orders->current());
if ($request->getMethod() === 'POST') {
/** @var array<string, mixed> $data */
$data = $request->getParsedBody();
$form->setData($data);
// Adding or removing a line only shows the form again
if (! $form->linesWereChanged() && $form->isValid()) {
/** @var Order $order */
$order = $form->getData();
// Save $order here
$flash->flash('status', "Saved order {$order->reference}. Total: {$order->total()}.");
return new RedirectResponse('/order', 303);
}
}
return new HtmlResponse($this->renderer->render('forms::order', [
'form' => $form,
'status' => $flash->getFlash('status'),
]));
}
}
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Csrf\CsrfGuardInterface;
use App\Forms\Order\Order;
use App\Forms\Order\OrderForm;
use App\Forms\Order\OrderProviderInterface;
use Laminas\Form\FormElementManager;
use Laminas\Http\Request;
use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Mvc\Plugin\FlashMessenger\FlashMessenger;
use Laminas\Stdlib\Parameters;
use Laminas\View\Model\ViewModel;
/** @api */
final class OrderController extends AbstractActionController
{
public function __construct(
private readonly FormElementManager $forms,
private readonly CsrfGuardInterface $guard,
private readonly OrderProviderInterface $orders,
) {}
public function formAction(): Response|ViewModel
{
$form = $this->forms->get(OrderForm::class);
$form->setCsrfGuard($this->guard);
// Fills the fields now, and receives the new values when they are valid
$form->bind($this->orders->current());
/** @var Request $request */
$request = $this->getRequest();
/** @var FlashMessenger $flash */
$flash = $this->plugin('flashMessenger');
if ($request->isPost()) {
/** @var Parameters $post */
$post = $request->getPost();
$form->setData($post->toArray());
// Adding or removing a line only shows the form again
if (! $form->linesWereChanged() && $form->isValid()) {
/** @var Order $order */
$order = $form->getData();
// Save $order here
$flash->addSuccessMessage("Saved order {$order->reference}. Total: {$order->total()}.");
return $this->redirect()->toRoute('order')->setStatusCode(303);
}
}
$view = new ViewModel([
'form' => $form,
'status' => $flash->getSuccessMessages()[0] ?? null,
]);
return $view->setTemplate('forms::order');
}
}
How it works
A collection repeats a fieldset. target_element says what to repeat. allow_add and allow_remove let the number of lines differ from the number the page started with. The data and the error messages are nested the same way as the fields: lines, then the line, then the field.
Buttons, not JavaScript. "Add another line" and "Remove line 2" submit the form. linesWereChanged() then tells the handler to show the form again without validating or saving, so half finished lines are left alone. formnovalidate stops the browser blocking these buttons because a field is empty.
Enter must not delete anything. Pressing Enter in a field uses the first submit button in the form. Without the extra "Save order" button at the top, that would be "Remove line 1". It is moved off screen and out of the tab order.
Tidy the lines before the form sees them. Sending lines=text where a list is expected makes Collection throw a TypeError. SubmittedLines drops whatever is not a line, replaces whatever is not text, and numbers the lines from zero.
count is not a minimum. It says how many blank lines to start with. An order sent with no lines at all would pass validation, so there is always at least one line, and its fields are required.
Nor is there a maximum. With allow_add, a request decides how many lines there are. The form keeps 20 and reports the rest through a hidden line_count field, so nothing is silently thrown away.
New objects, not reused ones. By default the collection gives the first submitted line to the first existing object, the second to the second, and so on. Remove line 1, and line 2's values land in line 1's object. Properties that are not fields, such as a database ID, would then belong to the wrong line. create_new_objects builds fresh objects instead.
Each line needs its own ids and a name. prepare() numbers the lines. The legend tells a screen reader which "Quantity" this is, and the error summary repeats it.
Keep your place. After adding a line, focus moves to it. After removing one, focus moves to "Add another line", so keyboard users are not sent back to the top of the page.
Say what changed. A removed line leaves no trace, and the lines after it are renumbered. A message says so, and aria-describedby makes it the description of the focused button, which screen readers can announce with it. A live region that is already there when the page loads may not be announced.
Money is not a float. Prices stay as text, and totals are counted in cents. Quantity and price are text inputs with inputmode, which shows a numeric keyboard without the surprises of type="number".
Before you use this for real
- Load the order by an ID you have checked belongs to the signed-in person.
- Save the order and its lines in one transaction where the "Save $order here" comment is.
- The "Add" and "Remove" buttons never call
isValid(), so the CSRF token is not checked for them. That is safe only while they save nothing. If you save a draft when they are pressed, validate the token first. - If your lines have database IDs, carry each in a hidden field and check that it belongs to this order. Otherwise replace all the lines when saving.
- Take prices from your catalogue if the person filling in the form must not choose them.
- Do not trust a total sent by the browser. Work it out on the server, as here.
- Check that PHP's
max_input_varsis large enough if you raise the line limit.
Further opportunities
None of these are built or tested here. Add the ones your site needs.
| Opportunity | Where | How |
|---|---|---|
| Add lines without reloading | A small script | Set should_create_template on the collection, and copy the template it renders. Keep the buttons for when the script fails |
| Show a running total | A small script | Update it as people type, and announce it politely. The server total stays the real one |
| Let people undo a removal | Form and template | Mark the line instead of dropping it |
| Reorder lines | Fieldset | Add a position field, or "Move up" buttons |
| Choose products | Fieldset | Replace the description with a select, filled by a factory |
| Skip blank lines | SubmittedLines |
Drop lines where nothing was typed, if empty ones should be forgiven |
| Handle currencies | Line |
Use a money library, and store cents with a currency code |
Common mistakes
- Expecting
countto require at least that many lines. - Giving every line the same
id, so labels and error links point at the first line. - Letting the browser validate the "Add" and "Remove" buttons.
- Putting a "Remove" button before the "Save" button and nothing in front of it.
- Setting
allow_addwithout limiting the number of lines. - Assuming submitted data has the shape of your form.