warmans/closureform

此包已被废弃,不再维护。没有建议的替代包。

生成和处理HTML表单的简单库。

dev-master 2014-02-04 12:12 UTC

This package is not auto-updated.

Last update: 2022-02-01 12:21:49 UTC


README

重用闭包进行表单生成的库。

示例可以在测试目录中找到,包括一系列单元测试(覆盖率99%+)。

<?php

$form = new \ClosureForm\Form('signup-form', array('method'=>'post', 'action'=>'#', 'class'=>'form'));

/* username */

$form->addTextField('email')
    ->label('Email Address')
    ->validator(function($value){
        //first validator
        if(strlen($value) < 3){
            return 'Email cannot be less than 3 characters';
        }
    })
    ->validator(function($value){
        //second validator
        if(!filter_var($value, FILTER_VALIDATE_EMAIL)){
            return "This is not a valid email address";
        }
    });

/* password + confirmation */

$form->addPasswordField('password')->label('Password')->validator(function($value){
    if(strlen($value) < 5){
        return 'Password cannot be less than 5 characters';
    }

});

$form->addPasswordField('confirm_password')->label('Confirm Password')->validator(function($value) use ($form) {
    //example of using another field's value in a field validator via the USE keyword
    if($value != $form->getField('password')->getSubmittedValue()){
        return 'Password Confirmation did not match password';
    }
});

/* submit */

$form->addButton('submit')->label('Submit')->action(function($form){
    if($form->isValid()){
        if(rand(1, 10) <= 5){
            $form->addError('We have decided to randomly reject your registration. Sorry!');
            return false;
        } else {
            return true;
        }
    }
});

$form->addButton('login')->label('or Login')->action(function($form){
    //dont't validate - we don't care if the form is valid
    header('Location:/some-login-page.php');
    exit();
});

/* process form if submitted */

if($form->handleButtonActions())
{
    echo 'Thank You, '.$form->getField('email')->getSubmittedValue();
}

/* output form */

echo $form->render();

输出(不含制表符,包括换行符)

<form name="signup-form" method="post" action="#" class="form">
    <input type="hidden" id="_internal_signup-form" name="_internal_signup-form" value="1"/>
    <div class="form-row"><label for="email">Email Address</label><input type="text" id="email" name="email" /></div>
    <div class="form-row"><label for="password">Password</label><input type="password" id="password" name="password" /></div>
    <div class="form-row"><label for="confirm_password">Confirm Password</label><input type="password" id="confirm_password" name="confirm_password" /></div>
    <div class="button-row">
        <button name="submit" >Submit</button>
        <button name="login" >or Login</button>
    </div>
</form>

待办事项

  • CSRF保护(当大多数人使用自己的会话处理器时,这并不容易)。会话保存处理器可以作为可选的闭包传递 - 否则可以使用原生的PHP会话处理。
  • 单选按钮
  • 字段数组(例如name[])
  • 字段集
  • 过滤器

可能待办事项