此包的最新版本(dev-master)没有可用的许可信息。

dev-master 2014-02-20 19:52 UTC

This package is not auto-updated.

Last update: 2024-09-23 15:13:20 UTC


README

Build Status Scrutinizer Quality Score Code Coverage

使用此包您可以做以下事情

  • 使用流畅的接口生成表单
  • 将其他模型中的数据呈现为选择字段,如选择列表、单选按钮或复选框。
  • 一次渲染整个表单,或者在视图脚本中仅渲染一个元素。
  • 与[Crud包](http://github.com/boyhagemann/Crud)结合使用,获得完整的后台管理权限!

安装

使用 [Composer](https://getcomposer.org.cn)将包安装到您的应用程序中

require {
    "boyhagemann/form": "dev-master"
}

然后在 app/config/app.php 中添加以下行

...
"Boyhagemann\Form\FormServiceProvider"
...

示例用法

<?php

use Boyhagemann\Crud\FormBuilder;


$fb = App::make('FormBuilder');

$fb->text('title')->label('Title')->rules('required|alpha');
$fb->textarea('body')->label('Body');
$fb->radio('online')->choices(array('no', 'yes'))->label('Show online?');
        
// You can use a fluent typing style
$fb->modelSelect('category_id')
   ->model('Category')
   ->label('Choose a category')
   ->query(function($q) {
     $q->orderBy('title');
   });
   
// Change an element
$fb->get('title')->label('What is the title?');
   

添加自定义元素

表单构建器被设置为灵活的系统,可以容纳许多自定义元素。元素的唯一条件是遵循 Boyhagemann\Form\Contract\HtmlElement 接口。要将新元素注册到表单构建器中,请执行以下操作

// Register the custom element to the FormBuilder instance.
// Please add elements in your service provider or in the application bootstrap.
$fb->register('myElement', 'The\Custom\Element\Class'); 

// We can now call the element and use it throughout your application
$fb->myElement('name');

为了在您的 IDE 中充分利用自动补全功能,请执行以下操作。您可以通过扩展表单构建器类并为您的应用程序创建一个基本表单。然后添加自定义元素的方法,如下所示

use Boyhagemann\Form\Formbuilder;

class MyBaseForm extends FormBuilder
{
    /**
     *
     * @param string $name
     * @return The\Custom\Element\Class
     */
    public function myElement($name)
    {
        return $this->element('myElement', $name, 'The\Custom\Element\Class');
    }
}

导出和导入

FormBuilder 可以通过 toArray 方法导出为数组。此数组可以存储为配置文件。

// Get the form as a config and store it in a file or session
$config = $fb->toArray();

// Then import it back again later to get the exact form
$fb->fromArray($config);

事件

在构建表单时触发几个事件

formbuilder.build.form.pre 允许您在构建过程开始之前修改表单构建器上的任何内容。

formbuilder.build.form.post 在构建表单之后,您可以挂钩到表单构建器以执行其他操作。或者,您可以与生成的表单 HTML 进行交互。

formbuilder.build.element.pre 在构建元素之前,您可以修改表单构建器实例或元素对象本身。

formbuilder.build.element.post 在元素构建之后,您可以对表单构建器实例或创建的元素 HTML 执行操作。

订阅者

订阅者是将事件和解决常见问题或帮助用户场景的结合。通过一行代码即可将它们添加到您的应用程序中。最好在您的 filters.phproutes.php 文件旁边创建一个 events.php 文件。以下是一些包含的订阅者

FillFormWithErrorsFromSession

当注册此订阅者时,您可以从会话中读取可能的错误。要使用它,只需将以下行添加到您的应用程序中。

Event::register('Boyhagemann\Form\Subscriber\FillFormWithErrorsFromSession');

SaveFormStateInSession

当您制作多页表单或想要去不同的页面然后再返回到您的表单时,您可能需要将表单值存储在会话中。此订阅者为您执行此操作。将此行添加到您的应用程序中

Event::register('Boyhagemann\Form\Subscriber\SaveFormStateInSession');