我想知道是否有人知道如何通过一个表单来编辑多个记录。此链接显示我正在寻找的确切内容:https://editor.datatables.net/examples/simple/multiRow.html。我已经创建了一个ajax调用,它将我选择的记录的id发送到我创建的editMultipleRecordsAction
方法。从那里我迷失了。任何提示都会非常感激(Symfony已经有了这方面的东西吗?我应该专门为此重建一个新的FormType吗?我应该使用相同的FormType但添加Listeners吗?我应该创建一个新的实体,其中我的id属性是一个数组? ...)。顺便说一下,我只有一个实体。
答案 0 :(得分:0)
我认为实现这一目标的最简单方法是:
$request->request->get('data');
Form::submit()
$form->isValid()
验证(每次迭代)$em->flush()
让学说计算变更集并保存到数据库这是一个未经测试的例子
public function editMultipleRecordsAction (Request $request)
{
// First we select what to do based on 'action' field (add/edit/delete)
switch ($request->request->get('action')) {
case 'edit':
// Fetch the payload
$data = $request->request->get('data');
// Fetch all edited entities
$entities = $this->getDoctrine()->getRepository('AppBundle:Entity')
->findBy(['id' => array_keys($data)]);
// Build a map of $id => $entity to use later
$map = [];
foreach ($entities as $entity) {
$map[$entity->getId()] = $entity;
}
if (array_keys($data) !== array_keys($map)) {
// Something went wrong, not all requested entities were fetched
}
// Loop over each edited entity
foreach ($data as $id => $form_data) {
// Create a form for the current entity (you can use createForm() as well, same thing)
$form = $this->createFormBuilder($map[$id])
// Notice that the id field is not part of the form
->add('name')
->add('position')
// ->add(...)
->getForm();
// Manually submit the data for this form
$form->submit($form_data);
if (!$form->isValid()) {
// Validation error, do something...
}
}
// Now we have iterated over each entity and updated it using Symfony's Form component
// The only thing remaining is to tell Doctrine to calculate the change set and save it to the database
$this->getDoctrine()->getManager()->flush();
// DataTables require that you return a JSON version of updated entities
// This will be different depending on what you use to serialize.
// The following example applies if you are using FOS Rest Bundle:
return $this->handleView($this->view(['data' => $entities]));
break;
case 'create':
// ...
break;
case 'remove':
// ...
break;
default:
throw new BadRequestHttpException();
}
}