berlioz/form

v0.3.3 2023-06-26 10:53 UTC

This package is auto-updated.

Last update: 2024-09-12 08:41:05 UTC


README

Latest Version Software license Build Status Quality Grade Total Downloads

Berlioz Form 是一个用于管理表单的 PHP 库。

安装

Composer

您可以使用 Composer 安装 Berlioz Form,这是推荐的安装方式。

$ composer require berlioz/form

依赖项

  • PHP ^8.0
    • berlioz/helpers
    • psr/http-message

描述

Berlioz Form 中存在 3 种类型的元素

  • AbstractType:表单控件
  • Group:表示面向对象中的对象
  • Collection:表示 AbstractType 或 Group 的集合

可用的输入类型

  • 按钮
  • 复选框
  • 选择
  • 日期
  • 日期时间
  • 电子邮件
  • 文件
  • 隐藏
  • 月份
  • 数字
  • 密码
  • 范围
  • 重置
  • 搜索
  • 提交
  • 电话
  • 文本
  • 多行文本
  • 时间
  • 网址

用法

表单创建

Form 对象的构造函数接受 3 个参数

  • 表单名称
  • 映射对象
  • 选项数组

示例

$form = new Form('my_form', null, ['method' => 'post']);

声明表单控件

add 方法接受 3 个参数

  • 控件名称(必须与映射元素相同)
  • 类型(类名或对象)
  • 选项数组

不同控件有不同的选项。

示例

$form->add('my_control', Text::class, ['label' => 'My control']);

处理

Berlioz Form 实现 PSR-7(HTTP 消息接口)。您必须将服务器请求传递给 handle 方法。

$form = new Form('my_form', null, ['method' => 'post']);
// ...

$form->handle($request);

if ($form->isSubmitted() && $form->isValid()) {
    // ...
}

邮政地址示例

$addressGroup = new Group(['type' => 'address']);
$addressGroup
    ->add('address', Text::class, ['label' => 'Address'])
    ->add(
        'address_next',
        Text::class,
        ['label' => 'Address (next)',
         'required' => false]
    )
    ->add('postal_code', Text::class, ['label' => 'Postal code'])
    ->add('city', Text::class, ['label' => 'City']);

$form->add('address', $addressGroup);

集合

地址列表示例

// Create group
$addressGroup = new Group(['type' => 'address']);
$addressGroup
    ->add('address', Text::class, ['label' => 'Address'])
    ->add(
        'address_next',
        Text::class,
        ['label' => 'Address (next)',
         'required' => false]
    )
    ->add('postal_code', Text::class, ['label' => 'Postal code'])
    ->add('city', Text::class, ['label' => 'City']);

// Create collection
$collection = new Collection([
    'prototype' => $addressGroup,
    'data_type' => ArrayObject::class
]);

// Add collection to form
$form->add('addresses', $collection);