ravengenocide/php-forms

该软件包最新版本(dev-master)没有提供许可证信息。

适用于PHP 5.4+的简单表单构建器

dev-master 2015-04-27 07:56 UTC

This package is not auto-updated.

Last update: 2024-09-28 18:26:29 UTC


README

适用于PHP 5.4+的表单构建器

一个实现了Validator接口的简单验证器。

预期功能

  1. 复制Laravel-form-builder。
  2. 允许像Django一样的输出,例如to_p、to_ul、(to_table)。
  3. 允许像Django一样创建对象,其中表单数据未输入到新创建的表单中,允许您重新渲染,或者在验证成功后继续。

验证

基于类的验证器

验证器实现Validator接口,并实现validate($value)函数。验证器要么返回null(表示验证成功),要么返回错误消息(表示验证失败)。

/*
 * A simple class-based validator that implements the Validator interface
 * This class does not do anything difficult, so we could just use a function based validator here
 */
class ValidatorYes implements Validator{
    public function validate($value){
        return "This is not right!";
    }
}

验证器函数

如果您不需要基于类的验证器的复杂性,可以直接传递一个函数,该函数接受一个值,并返回null或错误消息。

/*
 * This method will always fail the validation since it only returns a string
 */
function ValidatorYes($value){
    return "This is not right!";
}

创建时接受值的基于类的验证器

要查看一个更复杂的验证器的示例,我们可以看看PHPForms提供的RegexValidator。

class RegexValidator implements Validator {
    protected $regex;
    protected $message;
    protected $inverse_match;

    public function __construct($regex = "", $message = "", $inverse_match = false) {
        $this->regex = $regex;
        $this->message = $message;
        $this->inverse_match = $inverse_match;
    }

    public function validate($value) {
        if (!$this->inverse_match == preg_match($this->regex, $value)) {
            return null;
        } else {
            return $this->message;
        }
    }
}

要使用RegexValidator,您可以使用 new RegexValidator('/^$/', 'This is my message if the validator failed', false) 并在创建表单字段时传递它。

构建表单

Laravel表单构建器风格的表单构建

像Laravel表单构建器一样做,但不使用辅助工具

/*
 * Inheriting from Forms allows you to use it as LFB does
 */
class PostForm extends Forms {
    public function buildForm()
    {
        $this
            ->add('text', 'name', 'text', ['classes'=>['form-control']])
            ->add('textarea','lyrics', 'text')
            ->add('checkbox', 'publish', 'checkbox')
            ->add('button', '', 'submit',['value'=>'Submit']);
        return $this;
    }
}
$x = new PostForm();
echo $x->buildForm()->asDivs('form-group'); // This wraps the inputs in divs with the class form-group on them

复杂表单

一个大型示例,展示了多种执行操作的不同方法,验证器、addField、add、addButton方法、fieldsets等。

$formbuilder = new FormBuilder();

$fieldset = new \PHPForms\Fields\FieldsetField();
$fieldset->addField(new ButtonField('', 'button', ['value'=>'Empty click']));
$fieldset->addField(new LegendField('', '', ['value'=>'Testing, testing']));

$select = new \PHPForms\Fields\SelectField();
$select->addField(new \PHPForms\Fields\OptionField('','',['value'=>'1','text'=>'My text']));
$select->addField(new \PHPForms\Fields\OptionField('','',['value'=>'2', 'text'=>'Some other text']));

// The fields are instantiated with the values $name, $type, $options
// Text that should appear under value, is placed under $options['value'] and so on
// Attributes are placed under $options['attributes'] and css - classes $options['classes']

$formbuilder->addField(
        new FormField('test', 'number', ['value'=>"Test"], [new \PHPForms\Validators\ValueRangeValidator(1, 3, "Value must be between 1 and 3")/*, new \PHPForms\Validators\MinValueValidator(8, "Value must be at least 8.")*/, new \PHPForms\Validators\MaxValueValidator(5, "Value must be at most 5."), new \PHPForms\Validators\RegexValidator('/3/', "Must not be 3", true),
        new \PHPForms\Validators\RegexValidator('/2/', "Must be 2", false), function($value){
                return "No can do!";
            }])) // A lot of validators. Displaying Classbased validation and also method validation. This of course works if you pass a string to a method as well
    ->addButton('Submit', ['onclick' => 'alert("test")', 'style'=>'border:10px solid black;']) // A button added by the helper addButton, this will always create a submit button. Displaying setting onclick of the button, and also style
    ->addField(new ButtonField('', 'button', ['value'=>'Empty click','label'=>['wrap'=>true, 'value'=>'This is my label']])) // Button that is wrapped by a label with the text 'This is my label'
    ->addField(new ButtonButtonField('', '',['value'=>'Hello there']))
    ->addField(new PasswordField('password'))
    ->addField(new ButtonField('', 'submit', ['value'=>'Another one']))
    ->add('Button', '', '') // Generic add method. This tries to create a field with the class ButtonField
    ->add('Password', '','') // Generic add method. This tries to create a field with the class PasswordField, name = '', and type = '' since it doesn't care about type
    ->addField(new TextareaField('test-name', '', ['value'=>'Hello the textarea'])) // Textarea with name test-name, and the type doesn't matter. The text that will be in the textarea is given by 'value'=>'Hello the textarea'
    ->addField(new FormField('someothername', 'text')) // FormField is a generic field, so the element will be a <input name='someothername' type='text'> in this case
    ->addField($select) // Adding already created elements
    ->addField($fieldset); // Adding a fieldset, that is already created

echo $formbuilder->form->asParagraph();

格式化

基本输出格式化

您可以多次输出相同的表单。

echo $formbuilder->form->asDivs();

echo $formbuilder->form->asParagraph();

echo $formbuilder->form->asUnorderedList();

echo $formbuilder->form->asTable();

额外功能

更改方法

您还可以更改方法,然后再次输出,不会出现任何问题。

$formbuilder->form->setMethod('POST');

echo $formbuilder->form->asDivs();

添加数据

将数据添加到表单就像调用addData并用$_POST或$_GET一样简单。当然,您可以使用任何类型的数据,addData只需要一个关联数组。

if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $formbuilder->addData($_POST);
} else if($_SERVER['REQUEST_METHOD'] == 'GET'){
    $formbuilder->addData($_GET);
}

扩展

FieldContainer

由于PHP处理特性和接口的方式,我们无法真正检查一个类是否使用了特性,除非进行一些丑陋的检查。因此,当您想使用FieldContainerTrait时,您必须实现FieldContainerInterface。这是为了我们可以进行类提示,它仅适用于类和接口,而不适用于特性。