我正在使用数据库表将日志事件“翻译”成人类可读的等价物进行报告的日志解析器。
例如,类似“ start_application_minecraft”的日志条目将转换为“ Started Minecraft”。
我正在尝试制作一个用于添加/更新显示文本的Web界面,但是我不知道如何将它们放入Symfony Form对象中。
我有一个LogEvent
实体(与性质ID
,Text
和DisplayText
),和我创建了一个表单类型对应于这些属性。
它一次可以修改一个事件,效果很好,但是我想将它们全部都放在一个页面上,并用一个Submit按钮来更新所有内容。问题是我在嵌入表单时可以找到的所有文档都处理了相关的实体(例如,包含多个产品的类别),但是在我的情况下,我需要使用的所有实体都是完全不相关的。进行此设置的最佳方法是什么?
使用Symfony的“集合”表单字段类型,然后使用Doctrine查找所需的LogEvent实体并将其传递给集合。
示例:http://symfony.com/doc/current/cookbook/form/form_collections.html
参考:http : //symfony.com/doc/current/reference/forms/types/collection.html
因此,首先要使您的LogEvent表单类型为:
class LogEventType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('text');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'My\Bundle\Entity\LogEvent',
));
}
public function getName()
{
return 'log_event';
}
}
然后将您的表单类型保存为LogEvent实体的集合:
class MultiLogEventType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
'logEvents', 'collection', array('type' => new LogEventType())
);
}
public function getName()
{
return 'multi_log_event';
}
}
然后在Controller中,创建表单并将日志事件传递给它:
public function indexAction()
{
// replace findAll() with a more restrictive query if you need to
$logEvents = $this->getDoctrine()->getManager()
->getRepository('MyBundle:LogEvent')->findAll();
$form = $this->createForm(
new MultiLogEventType(),
array('logEvents' => $logEvents)
);
return array('form' => $form->createView());
}
然后,在您的编辑操作中,您可以遍历日志事件并执行所需的任何操作:
public function editAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$editForm = $this->createForm(new MultiLogEventType());
$editForm->handleRequest($request);
if ($editForm->isValid())
{
foreach ($logEvents as $logEvent) {
// perform any logic you need to here
// (ex: removing the log event; $em->remove($logEvent);)
}
$em->flush();
}
return $this->redirect($this->generateUrl('log_event_edit'));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句