Bonjour à tous,

J'ai un souci au niveau d'un handleRequest. J'ai un objet avec une liste de modèles :

<?php

namespace ManageBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints\Collection;
use FOS\ElasticaBundle\Configuration\Search;

/**
 * Description of CountryTechnologyModelList
 *
 * @author benjamin
 *
 * @ORM\Table(name="country_technology_model_list")
 * @ORM\Entity(repositoryClass="ManageBundle\Repository\CountryTechnologyModelListRepository")
 * @Search(repositoryClass="ManageBundle\RepositoryElastica\CountryTechnologyModelListRepositoryElastica")
 * @ORM\HasLifecycleCallbacks()
 */
class CountryTechnologyModelList extends Base {

    /**
     * @ORM\OneToOne(targetEntity="CountryTechnologyBase")
     * @ORM\JoinColumn(name="country_technology_base_id", referencedColumnName="id")
     */
    private $countryTechnologyBase;

    /**
     * @ORM\ManyToMany(targetEntity="TechnologyModel", inversedBy="countryTechnologyModelLists", cascade={"persist"})
     * @ORM\JoinColumn(nullable=true, onDelete="SET NULL")
     * */
    private $technologyModels;

    /**
     * Constructeur
     */
    public function __construct() {
        parent::__construct();
        $this->technologyModels = new ArrayCollection();
    }

    /**
     * Add technologyModel
     *
     * @param TechnologyModel $technologyModel
     *
     * @return CountryTechnologyClassement
     */
    public function addTechnologyModel(TechnologyModel $technologyModel)
    {

        if(!$this->technologyModels->contains($technologyModel)) {
            $technologyModel->getCountryTechnologyClassements()->add($this);
            $this->technologyModels->add($technologyModel);
        }

        return $this;
    }

    /**
     * Remove technologyModel
     *
     * @param TechnologyModel $technologyModel
     */
    public function removeTechnologyModel(TechnologyModel $technologyModel)
    {
        if($this->technologyModels->contains($technologyModel)) {
            $technologyModel->getCountryTechnologyClassements()->removeElement($this);
            $this->technologyModels->removeElement($technologyModel);
        }

        return $this;
    }

    /**
     * Get technologyModels
     *
     * @return Collection
     */
    public function getTechnologyModels()
    {
        return $this->technologyModels;
    }

    /**
     * Set countryTechnologyBase
     *
     * @param \ManageBundle\Entity\CountryTechnologyBase $countryTechnologyBase
     *
     * @return CountryTechnologyModelList
     */
    public function setCountryTechnologyBase(\ManageBundle\Entity\CountryTechnologyBase $countryTechnologyBase = null)
    {
        $this->countryTechnologyBase = $countryTechnologyBase;

        return $this;
    }

    /**
     * Get countryTechnologyBase
     *
     * @return \ManageBundle\Entity\CountryTechnologyBase
     */
    public function getCountryTechnologyBase()
    {
        return $this->countryTechnologyBase;
    }
}

Le controller :

/**
     * @Route("/save/model/list/{modelListId}", name="saveModelList")
     */
    public function saveModelListAction(Request $request, $modelListId) {

        $logger = $this->get('Logger');

        $em = $this->getDoctrine()->getManager();

        $countryModelList = $em->getRepository("ManageBundle:CountryTechnologyModelList")->findOneById($modelListId);

        $form = $this->get('form.factory')->create(new CountryModelListType(
                $countryModelList->getCountryTechnologyBase()->getTechnologyCategory()->getId()), $countryModelList);
        $form->handleRequest($request);

        $logger->info("Technology Models : " . count($countryModelList->getTechnologyModels()));

        if ($form->isValid()) {

            $em = $this->getDoctrine()->getManager();
            $em->persist($countryModelList);
            $em->flush();

            return new JsonResponse(array('message' => 'Success!'), 200);

        } else {

             $logger->info($form->getErrors()->__toString());
             $logger->info('class: ' . get_class($form));

            $viewModelList = $this->renderView('ManageBundle:Classement:Forms/form-country-model-list.html.twig', array('form' => $form->createView(),
                'countryTechnologyBaseId' => $countryModelList->getCountryTechnologyBase()->getId(),
                'action' => $this->generateUrl('saveModelList', array('modelListId' => $countryModelList->getId()))));

            return new JsonResponse(array('body' => $viewModelList), 400);
        }
    }

Le js qui envoie la liste des models :

             * Fonction pour sauvegarder la liste des modèles
             */
            function saveCountryTechnologyModelList() {

                var dataForm = $('#country_model_list_technologyModels').serialize();
                var urlSaveCountryModelList = $("#countryTechnologyModelListForm").attr('action');

                $.ajax({
                    type: "POST",
                    url: urlSaveCountryModelList,
                    data: dataForm,
                    async: false,
                    success: function (jsonResponse)
                    {
                        if (jsonResponse.return === 'modelsToDelete') {
                            var modelPositionIds = jsonResponse.modelPositionIds;
                            console.log(jsonResponse.modelPositionIds);
                            $.SmartMessageBox({
                                "title": "<i class='fa fa-warning ' style='color:red'></i> Certains modèles seront supprimés du classement",
                                "content": "" + jsonResponse.body + "",
                                "buttons": "[Annuler][Continuer]"
                            }, function (ButtonPressed) {
                                if (ButtonPressed === "Continuer") {
                                    var urlDeleteModelPositions = "{{ path('deleteModelPositionsBeforeSaveList') }}";
                                    $.ajax({
                                        type: "POST",
                                        url: urlDeleteModelPositions,
                                        data: 'modelPositionIds=' + modelPositionIds,
                                        async: false,
                                        success: function (jsonResponse2) {
                                            saveCountryTechnologyLists();
                                        }
                                    });
                                }
                            });
                        } else {
                            $.SmartMessageBox({
                                "title": "<i class='fa fa-check-circle-o ' style='color:green'></i> La liste des modèles a bien été sauvegardée.",
                                "content": "",
                                "buttons": "[OK]"
                            }, function (ButtonPressed) {
                                modelListChanged = false;
                                reloadClassement = true;
                            });
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown)
                    {
                        $.SmartMessageBox({
                            "title": "<i class='fa fa-warning ' style='color:green'></i> La liste des modèles n'a pas pu être sauvegardée.",
                            "content": "",
                            "buttons": "[OK]"
                        });
                    }
                });
            }

Quand j'essaie d'enregistrer cet objet avec une liste de TechnologyModels vide, l'enregistrement ne se fiat pas, le formulaire est non valide
mais je n'ai aucune erreur.

Et j'ai remarqué, par contre, que si je fais un $form->bind($request), alors là, ça fonctionne, l'objet est enregistré même avec la liste de smodels vide et je ne comprends pas pourquoi avec HandleRequest cela ne marche pas...

Aucune réponse