从没有表单/请求的数据数组中填充实体 [英] Populate entity from data array without form/request
问题描述
只是想知道是否可以只使用 symfony 表单处理的某些部分.例如,当通过 generate:doctrine:crud
创建 CRUD 操作时,我在我的控制器中得到一些东西(用于处理创建用户 POST 请求),如下所示:
Just wondering if it is possible to only use some parts of the symfony form handling. For exampe, when creating CRUD actions via generate:doctrine:crud
I get something in my Controller (for handling create User POST requests) that looks like this:
$entity = new User();
$form = $this->createForm(new UserType(), $entity,
array(
'action' => $this->generateUrl('user_create'),
'method' => 'POST',
));
$form->handleRequest($request);
//Here I have a filled Entity
但我想要的是在一个更可重用的解决方案中使用它.目前,我在名为 UserModel
的服务中有我的业务逻辑.在这里,我还希望使用 create
方法来创建、验证和持久化新实体.虽然 UserModel
也应该可以通过控制台从一些命令脚本中调用,所以我可能不会总是有 Request
或 Form
.
But what I want is to have this in a more reusable solution. Currently I have my business logic in a service called UserModel
. Here I also want to have the create
method to create, validate and persist a new entity. Tough the UserModel
should also be callable from some Command scripts via the console, so I probably won't always have Request
nor a Form
.
所以现在从上面的代码我知道 Symfony 已经根据 UserType
定义以某种方式将数据填充到实体,但是我怎么能在没有 Form
的情况下手动执行此操作code> 或 Request
而不是一些数据数组?
这样我就不必自己设置属性了.
So now from the above code I know that Symfony is already somehow populating data to an Entity according to the UserType
definition, but how could I do that manually without having a Form
or a Request
and instead just some array of data?
So that I don't have to take care of setting the properties myself.
验证对于填充实体没有问题,我稍后会在填充的实体上使用 validator
,然后再持久化数据.
对我来说同样重要的是传递的 related entity ids
将被自动处理/加载.
The validation is no issue for populating the entity, I'm using the validator
later on the populated entity before persisting the data.
And also important for me would be that the passed related entity ids
will be handled/loaded automatically.
推荐答案
你仍然可以使用 Form 组件,但是你应该直接使用 submit
而不是使用 handleRequest
.
you may still use the Form component, but instead of using handleRequest
, you should use directly submit
.
如果你好奇,你应该在 github 上查找 handleRequest
和 它实际做了什么 ;你会看到它只是做了一些验证,从 Request
和 然后使用表单的submit
方法.
If you are curious, you should look up the code on github for both handleRequest
and what it actually does ; you'll see that it just do some verification, takes the data from the Request
, and then uses the submit
method of the Form.
所以,基本上,您只能使用 submit
方法处理您希望使用的数据.它甚至可以验证您的实体.:)
So, basically, you can use only the submit
method with the data you wish to use. It even validates your entity. :)
更新
对于创建/更新相关实体的关注,如果您的关系有一个持久/更新级联,它应该从它自身推出而无需您做任何事情,除了在您的主实体上保持 + 刷新.
And for the concern of creating / updating related entities, if your relation have a persist / update cascade, it should roll out from itself without you doing a single thing, except persist + flush on your main entity.
这篇关于从没有表单/请求的数据数组中填充实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!