andersondanilo/modelform

ModelForm 是一个基于 Django Forms 和 Formset 的 Laravel 表单抽象,但完全与 Laravel FormBuilder 集成。

1.0.1 2015-01-31 00:31 UTC

This package is auto-updated.

Last update: 2024-08-27 04:01:42 UTC


README

Travis Code Climate Test Coverage Latest Stable Version Latest Unstable Version License

是什么

ModelForm 是一个基于 Django Forms 和 Formset 的 Laravel 表单抽象,但完全与 Laravel FormBuilder 集成。

安装

要获取 ModelForm 的最新版本,只需在 composer.json 文件中引入它。

php composer.phar require "andersondanilo/modelform:dev-master"

使用示例

简单示例:没有模型

// SimpleForm.php
use ModelForm\Form;
use ModelForm\Fields\CharField;
use ModelForm\Fields\IntegerField;

class SimpleForm extends Form
{
    public function makeFields()
    {
        $this->name = new CharField(['label' => 'Name']);
        $this->age = new IntegerField(['label' => 'Age']);
    }
}

实例化表单

$simpleForm = new SimpleForm(['data' => Input::old() ?: Input::all()]);

在视图中渲染模型

    {{ $simpleForm->name->label() }}:
    {{ $simpleForm->name->text(['class' => 'form-control']) }}

之后访问值

    $name = $simpleForm->name->value;

带有模型和验证器

use ModelForm\Form;
use ModelForm\Fields\CharField;
use ModelForm\Fields\IntegerField;

class SimpleForm extends Form
{
    public function makeFields()
    {
        $this->name = new CharField(['label' => 'Name']);
        $this->age = new IntegerField(['label' => 'Age']);
    }
    
    public function makeModel()
    {
        return new MyModel();
    }
    
    public function makeValidator($data)
    {
        return Validator::make($data, [
            'name' => 'required'
        ]);
    }
}

您可以不使用模型实例化,然后由表单创建模型,或者从已经存在的模型开始。

$model10 = MyModel::find(10);
$form = new SimpleForm(['model' => $model10, 'data' => Input::old() ?: Input::all()]);

验证

if(!$simpleForm->isValid()) {
    return Redirect::back()->withErrors($simpleForm->errors())->withInput();
}

保存您的模型

$simpleForm->save();

表单集

use ModelForm\FormSet;

class SimpleFormSet extends FormSet
{
    public function makeForm($model=null)
    {
        return new SimpleForm(['model'=>$model]);
    }
}

创建空的表单集实例

$simpleFormSet = new SimpleFormSet(['data' => Input::old() ?: Input::all());

或者创建一个包含模型关系的表单集

$addressFormSet = new AddressFormSet(['relation'=>$customer->addresses(), 'data' => Input::old() ?: Input::all());

表单集的验证和保存与表单是对称的。

if(!$addressFormSet->isValid()) {
    return Redirect::back()->withErrors($addressFormSet->errors())->withInput();
}
$addressFormSet->save();