[英]Populate a second entity after a form submit in Symfony2
I'm recently new Symfony (2.8) and I'm trying, that after an image file submission from a form, is to populate a second entity with the mains colors of the image.我最近是新的 Symfony (2.8) 并且我正在尝试,在从表单提交图像文件之后,用图像的主要颜色填充第二个实体。
For now, I just made a test from the controller like this:现在,我只是从控制器进行了这样的测试:
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($image);
$extractor->setImage($image->getFile());
$palette = $extractor->extractPalette();
foreach($palette as $color => $weight){
$imageColor = new Color();
$imageColor->setImage($image);
$imageColor->setRgb($color);
$imageColor->setWeight($weight);
$em->persist($imageColor);
}
$em->flush();
It's working but I don't think that the colors should be in the form or the controller neither is the image entity.它正在工作,但我不认为颜色应该在表单或控制器中,也不是图像实体。 So, how should I deal with the colors ?
那么,我应该如何处理颜色?
I have two solutions in mind to save Colors
outside your controller:我有两种解决方案可以将
Colors
保存在控制器之外:
Create a Doctrine listener (on prePersist and preUpdate) that will generate Colors
when an Image
is persisted.创建一个 Doctrine 侦听器(在 prePersist 和 preUpdate 上),它将在
Image
持久化时生成Colors
。
Before flush
, dispatch a custom Event and catch it with an EventListener.在
flush
之前,调度自定义 Event 并使用 EventListener 捕获它。 When caught, execute method that populate Colors
.捕获后,执行填充
Colors
方法。
Advantage of solution 1: Colors
will automatically be generated for an Image
, whether you are in a Controller, a Command, or somewhere else.方案一的优点:不管你是在Controller、Command还是其他地方,都会自动为
Image
生成Colors
。
Advantage of solution 2: You can decide more precisely when you want to generate Colors, by dispatching your custom event.解决方案 2 的优势:通过调度自定义事件,您可以更准确地决定何时生成颜色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.