handleRequest() fausse les données envoyées
Bonjour tout le monde,
Je rencontre un problème très étrange dans un controlleur au moment de mon handleRequest($this->getRequest()).
Pour essayer de détailler clairement et simplement :
Un controlleur dans lequelle je construis deux forms, je handleRequest() pour mes deux formulaires, mais si le premier a été validé, alors les données récupérées sont bizarres.
Petit exemple de scénario :
1) Je clique sur un lien me dirigeant vers la page où mes deux formulaires sont affichés
2) Aucune données ne sont encore affichées car rien en BDD. Mes formulaires s'affichent donc sans datas.
3) Jajoute des données et clique pour sauvegarder, cela me redirige vers la page précédente. (en BDD les lignes sont créées)
4) Je recommence l'étape 1. (en BDD les lignes sont toujours là)
5) Le formulaire contient bien les données que je viens de renseigner.(en BDD les lignes sont toujours là)
6) Je reclique sur le bouton pour sauvegarder et revenir à la page précédente.(en BDD ldeux lignes ont été supprimées)
7) Je recommencde l'étape 1.
8) Le formulaire s'affiche mais une seule ligne est affichée.
A force de var_dump(), il semble que lorsque le handleRequest() s'execute, il "oublie" deux lignes de mon formulaire...
Je tourne en rond depuis pas mal de temps sans trouver la moindre piste.
Je vous fournis mon controlleur et mon twig. (dites moi si vous avez besoin d'autre chose :-) )
Controlleur :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
<?php
namespace ATS\CapacityPlanBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use ATS\CapacityPlanBundle\Form\Type\ResourcePickListContainerType;
use ATS\CapacityPlanBundle\Form\Type\ServicesApplicationResourcesManagementType;
use ATS\CapacityPlanBundle\Entity\ServicesApplication;
class ServicesApplicationController extends Controller
{
/**
*
* @return render
*/
public function viewAction($id)
{
$em = $this->getDoctrine()->getManager();
$rep = $em->getRepository('ATSCapacityPlanBundle:ServicesApplication');
$serviceApplication = $rep->find($id);
$applicationId = $serviceApplication->getApplication()->getId();
$projectId = $serviceApplication->getApplication()->getProject()->getId();
$route = 'ats_capacity_plan_applicationManagement';
// Get forms to display Config
$formServAppliToDisplay = $this->createForm(new ServicesApplicationResourcesManagementType($em), $serviceApplication);
$formResourcesPickList = $this->createForm(new ResourcePickListContainerType($em));
// Get Original Resources --> Will be used to know if some if its has been deleted
$originalResources = new \Doctrine\Common\Collections\ArrayCollection();
foreach ($formServAppliToDisplay->getData()->getResources() as $resource) {
$originalResources[]=$resource;
}
//Bind Datas
$formServAppliToDisplay->handleRequest($this->getRequest());
$formResourcesPickList->handleRequest($this->getRequest());
if($formServAppliToDisplay->isValid())// User has clicked on submit and datas are correct
{
$resourcesAdded = new \Doctrine\Common\Collections\ArrayCollection();
if (!is_null($formResourcesPickList->getData())) {
// We check new resources added through the resource picklist form
// We add it to the ServiceApplication if the picklist value is not null
foreach ($formResourcesPickList->getData() as $value) {
foreach ($value as $resource) {//loop on all services picklist
if (!is_null($resource['resources'])) {
$resourcesAdded[] = $resource['resources'];
$resource['resources']->addServicesApplication($formServAppliToDisplay->getData());
$formServAppliToDisplay->getData()->addResource($resource['resources']);
}
}
}
}
/*
* CHECK POURQUOI ON RENTRE DANS LA BOUCLE CI DESSOUS !!!!!!!
*/
foreach ($originalResources as $res) {
// We checked if the ServiceApplicationResources in db is still in the ServiceApplication sended through the form
// If no --> it has been deleted by the user
if (!$formServAppliToDisplay->getData()->getResources()->contains($res) && !$resourcesAdded->contains($res)){
$res->removeServicesApplication($serviceApplication);
$serviceApplication->removeResource($res);
}
}
foreach ($formServAppliToDisplay->getData()->getResources() as $value) {
$value->addServicesApplication($formServAppliToDisplay->getData());
}
try {
$this->updateServiceApplication($formServAppliToDisplay->getData()); // Persist infos in DB
//return $this->redirect($this->generateUrl($route, array('id'=>$applicationId)));
} catch (\Exception $exc) {
print('An error happened inserting datas in Database ! </br></br>'.$exc->getMessage()
.'</br></br>Please come back to the last page and correct datas you tried to send.');
exit;
}
}
$args = array(
'projectId' => $projectId,
'formResourcesPicklist' => $formResourcesPickList->createView(),
'formServiceApplication' => $formServAppliToDisplay->createView(),
'ServiceApplication' => $formServAppliToDisplay->getData(),
);
return $this->render('ATSCapacityPlanBundle:ServiceApplication:ServicesApplicationManagement.html.twig', $args);
}
/**
* Function to update a serviceApplication in DB
* @param type $project
* @param type $id
*/
public function updateServiceApplication($serviceApplication)
{
$em = $this->getDoctrine()->getManager();
$em->persist($serviceApplication);
$em->flush(); // Save the Project with new datas in DB
}
} |
TWIG :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
|
{% extends "::GeneralTemplate.html.twig" %}
{% block menu %}
<div id="menubar">
<ul id="menu">
<!-- put class="selected" in the li tag for the selected page - to highlight which page you're on -->
<li class="selected"><a href={{ path('ats_capacity_plan_configurationview', { 'id' : projectId }) }}>Configuration</a></li>
<li><a href={{ path('ats_capacity_plan_availability', { 'id' : projectId }) }}>Availability</a></li>
<li><a href={{ path('ats_capacity_plan_plan', { 'id' : projectId }) }}>Plan</a></li>
<li><a href={{ path('ats_capacity_plan_demands') }}>Demands</a></li>
<li><a href={{ path('ats_capacity_plan_capacitytable') }}>Capacity Table</a></li>
<li><a href={{ path('ats_capacity_plan_balance') }}>Balance</a></li>
</ul>
</div>
{% endblock %}
{% block body %}
{# On charge la bibliothèque jQuery. Ici, je la prends depuis le CDN google
mais si vous l'avez en local, changez simplement l'adresse. #}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/fixedcolumns/3.2.0/js/dataTables.fixedColumns.min.js"></script>
{{ form_start(formServiceApplication) }}
<div id="menu"><h2>List of Resources for {{ ServiceApplication.getApplication.getText }} - {{ ServiceApplication.getServiceName }}</h2><hr></div>
<table id="resources">
{% if formServiceApplication.resources|length > 0 %}
{% for resource in formServiceApplication.resources %}
{{ form_start(resource) }}
<tr id="resource">
<td>{{ form_widget(resource.firstName) }} {{ form_widget(resource.lastName) }}</td>
</tr>
{{ form_rest(resource) }}
{{ form_end(resource) }}
{% endfor %}
{% endif %}
{% if formServiceApplication.resources|length <= 0 %}
<tr id="resource">
<td>No resource saved yet</td>
</tr>
{% endif %}
<tr id="buttons"><td><button id="addResource" class="btn">Add Resource</button></td><td>{{ form_widget(formServiceApplication.save) }}</td></tr>
</table>
{{ form_rest(formServiceApplication) }}
{{ form_end(formServiceApplication) }}
{{ form_start(formResourcesPicklist) }}
{{ form_end(formResourcesPicklist) }}
{# Partie JavaScript : #}
<script type="text/javascript">
var $index = 0;
var $count = 0;
$(document).ready(function() {
//var $applicationId = $(".applicationId").data("applicationid");
// On récupère la table ayant pour id : assumptions
var $containerResources = $('table#resources');
// On ajoute un lien de suppression à la fin de chaque ligne de notre tableau d'application services
$containerResources.find('tr#resource').each(function() {
addDeleteLink($(this), "Please confirm deletion of that resource");
});
/*---------------------------------------------------------------------------------------------------*/
/*------------------------------------ EXISTING RESOURCE PICKLIST ----------------------------------*/
/*---------------------------------------------------------------------------------------------------*/
$('button#addResource').on('click', function(e) {
// Get the html for adding a resource picklist
var $newResource = $('div#ProjectResources_resources').data('prototype');
var $newForm = '<tr><td>' + $newResource.replace(/__name__/g, 'resource' + $index) + '</td></tr>';
var $formResource = $($newForm);
$index++;
addDeleteLink($formResource, "Please confirm deletion of that resource");
// prevent the link from creating a "#" on the URL
e.preventDefault();
// Add a resource picklist
$('tr#resource:first').before($formResource);
});
/*---------------------------------------------------------------------------------------------------*/
/*----------------------------------------- DELETION ----------------------------------------------*/
/*---------------------------------------------------------------------------------------------------*/
// La fonction qui ajoute un lien de suppression à la fin d'un formulaire
function addDeleteLink($form, $message) {
// Construction de l'objet HTML de Suppression de formulaire
var $removeFormA = $('<a href="#" class="btn">X</a>');
// On l'ajoute à la fin de l'objet HTML passé à la fonction
$form.append($removeFormA);
// A chaque clic sur le bouton on enlève le formulaire associé au lien
$removeFormA.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
if(confirm($message)){
$form.remove();// suppression du <tr><td> correspondant
}
// On vérifie que l'on n'a pas supprimé pas la dernière resource, auquel cas on affiche "No resource saved yet"
$containerResources.find('tr#resource').each(function() {
$count++;
});
if($count<1){
$('tr#buttons').before('<tr id="resource"><td>No resource saved yet</td></tr>');
}
$count=0;
});
}
} );
</script>
{% endblock %} |
Merci d'avance de votre aide !
Emmanuel