asgard / entityform
Requires
- php: >=5.5.9
- asgard/entity: ~0.3.0
- asgard/form: ~0.3.0
This package is not auto-updated.
Last update: 2024-09-14 06:52:24 UTC
README
#EntityForm
Entityform 帮助您从实体生成表单。它创建与所有实体属性对应的表单字段。Entityform 是 Form 的子类。
##安装 如果您正在处理一个 Asgard 项目,您不需要安装此库,因为它已经是标准库的一部分。
composer require asgard/entityform 0.*
##Asgard 框架中的使用 使用表单服务的好处是它会为 Form 提供所有必要的依赖项
$request = \Asgard\Http\Request::CreateFromGlobals();
$entity = new Article;
$container->make('entityForm', [
$entity, #required
[ #optional
'action' => 'form.php',
'enctype' => 'multipart/form-data',
'attrs' => [
'class' => 'formClass'
]
],
$request, #optional, Asgard can provide the form with the current request
]);
container 通常作为方法参数或通过 ContainerAware 对象访问。您也可以使用 singleton,但不推荐这样做。
##框架外的使用 在这里,您必须自己提供依赖项(参见下一节)
$entityFieldsSolver = new \Asgard\Entityform\EntityFieldsSolver;
$request = \Asgard\Http\Request::CreateFromGlobals();
$entity = new Article;
$form = new \Asgard\Entityform\Entityform(
$entity, #required
[ #optional
'action' => 'form.php',
'enctype' => 'multipart/form-data',
'attrs' => [
'class' => 'formClass'
]
],
$request, #optional, if not request is provided the form will automatically use \Asgard\Http\Request::createFromGlobals()
$entityFieldsSolver #optional, Asgard can automatically retrieve an instance of EntityFieldsSolver
);
##添加实体关系
如果实体表单是从具有 "comments" 关系的实体创建的,您可以使用以下方法将其嵌入到表单中
$form->addRelation('comments');
这将添加一个用于选择与实体相关的评论的字段。适用于所有类型的关联,"one" 和 "many"。
##保存实体
要保存实体,只需这样做
$form->save();
如果存在验证错误,它将抛出异常 \Asgard\Form\FormException。有关如何处理异常和错误的说明,请参阅 Form 文档。
##获取实体
$form->getEntity();
##EntityFieldSolver
为了告诉 entityform 如何从实体属性创建字段,您可以使用 Asgard\Entityform\EntityFieldsSolver 类。默认情况下,它已经处理了 Text、text、Double、Integer、Email、Boolean、Date、Datetime、File 实体属性(所有在 Asgard\Entity\Property\ 中)。如果 EntityFieldsSolver 未知特定属性的表单类型,它将默认返回 \Asgard\Form\Field\TextField 字段。
要扩展 entityFieldsSolver,添加一个返回表单字段对象的回调函数
$cb = function(\Asgard\Entity\Property $property) {
if(get_class($property) == 'Asgard\Entity\Property\DateProperty')
return new MyOwnDateField;
};
$fieldsSolver->add($cb);
对于具有多个值的实体属性,使用
$cb = function(\Asgard\Entity\Property $property) {
if(get_class($property) == 'Asgard\Entity\Property\DateProperty')
return new \Asgard\Form\DynamicGroup;
};
$fieldsSolver->addMany($cb);
如果回调返回 null,则将其忽略。
您还可以嵌套其他 solvers
$anotherFieldsSolver->addSolver($fieldsSolver);
如果 $anotherFieldsSolver 无法解决字段,它将请求嵌套 solvers。
解决实体属性的表单字段
$form->solve($Definition->getProperty('title'));
从表单获取 EntityFieldSolver
$fieldsSolver = $form->getEntityFieldsSolver();
为表单设置 EntityFieldsSolver
$form->addEntityFieldsSolver($cb);
###贡献
请将所有问题和拉取请求提交到 asgardphp/asgard 仓库。
许可
Asgard框架是开源软件,许可协议为MIT许可协议