First I've read documents for both Collection Field Type and How to Embed a Collection of Forms ... The example is about one entity (Task) that has one-to-many relation with another entity (Tag), and I understand it, but I can not adapt it to what I want!
To make it simpler, let say I have a Task entity, this task entity has some relations with other objects like user and project (each task can have one user and one project)
I want to make one form, inside this form a list of Tasks, each task in one row of a table that shows information like task.title, task.startdate, task.user.name, task.user.company.name, task.project.name, And it has 2 fields editable, textbox "Description" and checkbox "active". You can edit multiple tasks and submit the form using one button at the bottom of the table in the main form, so basically you should be able to update multiple records in one transaction (instead of making one form and one submit button per row and therefor one record update per submit).
I have many issues with this complicated design:
First I wanted to follow the sample to embed a collection of forms inside the main form, So I made a Form Type for my Task that should be like one form per row. I made these files:
Form Type for Task:
// src/Acme/TaskBundle/Form/Type/TaskType.php
namespace Acme\TaskBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TaskType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('description', 'text', ['label' => false, 'required' => false, 'attr' => ['placeholder' => 'description']]);
$builder->add('active', 'checkbox', ['label' => false, 'required' => false, 'data' => true]);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\TaskBundle\Entity\Task',
));
}
public function getName()
{
return 'taskType';
}
}
Form Type for main form:
// src/Acme/TaskBundle/Form/Type/SaveTasksType.php
namespace Acme\TaskBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Acme\TaskBundle\Form\Type\TaskType.php;
class SaveTasksType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('tasksCollection', 'collection', ['type' => new TaskType()]);
$builder->add('tasksSubmit', 'submit', ['label' => 'Save']);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults([
'attr' => ['class' => 'form-horizontal'],
'method' => 'POST'
]);
}
public function getName()
{
return 'saveTasksType';
}
}
Tasks Form Controller:
// src/Acme/TaskBundle/Controller/ManageTasksController.php
namespace Acme\TaskBundle\Controller;
use Acme\TaskBundle\Entity\Task;
use Acme\TaskBundle\Form\Type\SaveTaskType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ManageTasksController extends Controller
{
public function showListAction(Request $request)
{
$repository = $this->getDoctrine()->getRepository('ExampleBundle:Task');
$tasks = $repository->findAll();
$taskSaveForm = $this->createForm(new SaveTasksType(['tasks' => $tasks]));
return $this->render('AcmeTaskBundle:Task:list.html.twig', array(
'taskSaveForm' => $taskSaveForm->createView(),
));
}
}
Task Form Twig Template (just related part):
<div class="innerAll">
{{ form_start(taskSaveForm) }}
{{ form_errors(taskSaveForm) }}
<table class="table table-bordered table-striped table-primary list-table">
<thead>
<tr>
<th>Task ID</th>
<th>Title</th>
<th>Start Date</th>
<th>User</th>
<th>Company</th>
<th>Project</th>
<th>Description</th>
<th>Active</th>
</tr>
</thead>
<tbody>
{% for task in taskSaveForm.tasksCollection %}
<tr>
<td>{{ task.id }}</td>
<td><a href="https://localhost/taskid={{ task.id }}">{{ task.title }}</a></td>
<td>{{ task.startDate }}</td>
<td>{{ task.userName }}</td>
<td>{{ task.companyName }}</td>
<td>{{ task.projectName }}</td>
<td>{{ form_widget(task.description) }}</td>
<td>{{ form_widget(task.active) }}</td>
<td></td>
</tr>
{% endfor %}
</tbody>
</table>
<div>{{ form_row(taskSaveForm.tasksSubmit) }}</div>
{{ form_end(taskSaveForm) }}
</div>
BUT there is an issue here, when I get the result from query builder it is a mess of arrays containing objects in them, I get an error about
The form's view data is expected to be an instance of class Acme\TaskBundle\Entity\Task, but is a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of Acme\TaskBundle\Entity\Task.
This is the query:
createQueryBuilder()
->select(
"
task.id,
task.title,
task.startDate,
task.description,
user.name as userName,
company.name as companyName,
project.name as projectName,
"
)
->from('Acme\TaskBundle\Entity\Task', 'task')
->innerJoin('task.project', 'project')
->innerJoin('task.user', 'user')
->innerJoin('Acme\TaskBundle\Entity\Company', 'company', 'with', 'store.company = company')
->where('task.active = :isActive')->setParameter('isActive', true);
Soooo, I used Partial Objects guide to see if it can help, it helps to make the task object in the query result and I could extract it and send it to form, but still it seems the rest of form is unaware of the rest of objects...
Ok, so maybe I'm choosing the wrong approach, I'm not sure! please if you have any suggestions about what should I do, put a note here... I'm struggling with this for more than a week! Thanks in advance for your time! Even if you don't put any note, I appreciate that you spend time reading my very long question! Thanks! :)
Here's a start on a possible solution. The example below takes a single entity Skills and presents all of them on a single page. What I don't know is whether this technique can be used to persist children objects. I would expect one could loop through the returned data and persist as required.
The code below results in a page with a list of all possible Skills and a checkbox for declaring each enabled or enabled.
In a controller:
$skills = $em->getRepository("TruckeeMatchingBundle:Skill")->getSkills();
$formSkills = $this->createForm(new SkillsType(), array('skills' => $skills));
...
if ($request->getMethod() == 'POST') {
$formSkills->handleRequest($request);
foreach ($skills as $existingSkill) {
$em->persist($existingSkill);
}
}
...
return ['formSkills' => $formSkills->createView(),...]
In a template:
{% for skill in formSkills.skills %}
{{ skill.vars.value.skill }}
<input type="hidden" name="skills[skills][{{ loop.index0 }}][skill]" value="{{ skill.vars.value.skill }}">
<input type="checkbox" name="skills[skills][{{ loop.index0 }}][enabled]"
{%if skill.vars.value.enabled %}checked="checked"{%endif%}
{% endfor %}
I use a different strategy. My TWIG file is similar to that of Monica's question. But has a few but very useful differences. Here your code:
{{ form_start(form) }}
{% for docente in docentes %}
Id: <input type="integer" name="{{ docente.id }}" required="required" style="width:30px" value="{{ docente.id }}" readonly>
Apellido: <input type="text" name="{{ docente.apellido }}" required="required" style="width: 80px" value="{{ docente.apellido }}" readonly>
Nombres: <input type="text" name="{{ docente.nombres }}" required="required" style="width: 80px" value="{{ docente.nombres }}" readonly>
Discrecional: <input type="checkbox" name="D{{ docente.id }}" value="{{ docente.discrecional }}" {% if docente.discrecional==1 %}checked{% endif %}> <br>
<br>
{% endfor %}
<input type="submit" value="Grabar" />
{{ form_end(form) }}
In TWIG file, I proceed to create a different name for each record in the form for the "discrecional" field. This will help me to identify each record in the controller. Watch up.
Once the user presses the "submit" button I perform an iteration in my Controller file, as shown below:
if ($form->isSubmitted() && $form->isValid()) {
$i=0;
foreach ($defaultData as $value) {
$data2= array('id' =>$request->request->get($defaultData[$i]['id']),
'discrecional' =>$request->request->get('D'.$defaultData[$i]['id']));
if (($request->request->get('D'.$defaultData[$i]['id'])== '0' and $defaultData[$i]['discrecional']=='0') or
($request->request->get('D'.$defaultData[$i]['id'])== NULL and $defaultData[$i]['discrecional']=='1'))
{
$em->getRepository('BackendBundle:Docentes')->findDocenteFiltId2($data2);
}
$i=$i+1;
}
But the update of registers, is a work that is done in my Repository file through a query using UPDATE, instead of doing it in the Controller file. To avoid unnecessary queries and a server overload, I only do an UPDATE of records that have previously changed. In the example, the following lines in my controller check if there has been a change in the record (in my case, I'm just editing a field called "discrecional". If the field has changed, then I call the query and update the record):
if (($request->request->get('D'.$defaultData[$i]['id'])== '0' and $Data[$i]['discrecional']=='0') or
($request->request->get('D'.$defaultData[$i]['id'])== NULL and $defaultData[$i]['discrecional']=='1'))
{
$em->getRepository('BackendBundle:Docentes')->findDocenteFiltId2($data2);
}
My complete Controller file is here:
public function discrecionalAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$defaultData= $em->getRepository('BackendBundle:Docentes')->buscarDocentesActivos2();
// construimos un formulario "vacío" sin campos definido
$form = $this->createFormBuilder($defaultData);
$form = $form->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$i=0;
foreach ($defaultData as $value) {
$data2= array('id' =>$request->request->get($defaultData[$i]['id']),
'discrecional' =>$request->request->get('D'.$defaultData[$i]['id']));
if (($request->request->get('D'.$defaultData[$i]['id'])== '0' and $defaultData[$i]['discrecional']=='0') or
($request->request->get('D'.$defaultData[$i]['id'])== NULL and $defaultData[$i]['discrecional']=='1'))
{
$em->getRepository('BackendBundle:Docentes')->findDocenteFiltId2($data2);
}
$i=$i+1;
}
return $this->redirectToRoute('docentes_discrecional');
}
return $this->render('docentes/discrecional.html.twig', array(
'docentes' =>$defaultData,
'form' => $form->createView() ));
}
My complete first Repository query is here:
public function buscarDocentesActivos2()
{
$fields = array('d.id', 'd.apellido', 'd.nombres', 'd.discrecional');
$query = $this->getEntityManager()->createQueryBuilder();
$query
->select($fields)
->from('BackendBundle:Docentes', 'd')
->where('d.activo=true')
->orderBy('d.apellido, d.nombres');
$consulta = $query->getQuery()->getResult();
return $consulta;
}
My complete final Repository query with the UPDATE function is here:
public function findDocenteFiltId2($filtro)
{
if (is_null($filtro['discrecional'])){
$discrec= '0';
};
if ($filtro['discrecional']=='0'){
$discrec= '1';
};
$em = $this->getEntityManager();
$consulta = $em->createQuery('
UPDATE BackendBundle:Docentes d
SET d.discrecional = :disc
WHERE d.id = :idver
');
$consulta->setParameters(array(
'idver' => $filtro['id'],
'disc' => $discrec,
));
return $consulta->getArrayResult();
}
来源:https://stackoverflow.com/questions/27953858/how-to-create-a-form-with-multiple-rows-of-one-entity-in-symfony2