Skip to content

Forms and validation

Entity managers expose a form generated from the entity annotations supported by small/forms:

use Small\Collection\Collection\StringCollection;

$form = $userManager->getForm();
$form->fillFromArray($requestBody);

$messages = new StringCollection();
$form->validate($messages);

if ($messages->count() > 0) {
    $errors = $messages->toArray();
}

/** @var UserEntity $user */
$user = $userManager->newEntity();
$form->hydrate($user);
$user->persist();

getForm() creates a new entity and passes it through Small\Forms\Adapter\AnnotationAdapter, then builds the form with FormBuilder.

Useful input helpers are:

  • fillFromArray();
  • fillFromJson();
  • fillFromUrlEncodedString();
  • fillFromObject().

validate() appends errors to a StringCollection. Pass true as its second argument when validation should throw on the first completed validation pass containing errors.

Validation constraints and form behavior come from the small/forms package and the annotations placed on the entity. The ORM itself does not automatically validate an entity during persist(); validate or hydrate through a form before persistence when input is user-controlled.

For partial updates, combine form hydration with notPersist() or use an update builder.

Next chapter: Database layers