0

I am using zendframework 2 and doctrine 2. My addAction doesn't work i don't have any error but when i valid my form no row created in my database !! i think that i have problem in populating foreign key ! this is my Form:

<?php
// filename : module/Users/src/Users/Form/addForm.php
namespace Vehicules\Form;
use Zend\Form\Form;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Doctrine\Common\Persistence\ObjectManager;
class VehiculeForm extends form implements ObjectManagerAwareInterface
{ 
protected $objectManager;
public function setObjectManager(ObjectManager $objectManager)
{
    $this->objectManager = $objectManager;
}

public function getObjectManager()
{
    return $this->objectManager;
}
    //public function init()
public function __construct(ObjectManager $objectManager)
{
    parent::__construct('add');

    $this->objectManager = $objectManager;
    $this->init();
}
    public function init(){
        $this->setAttribute('method', 'post');
        $this->setAttribute('enctype','multipart/formdata');
        $this->add(array(
                'name' => 'matricule',
                'attributes' => array(
                        'type' => 'text',
                        'required' => true
                ),
                'options' => array(
                        'label' => 'Matricule',
                ),
        ));


        $this->add(array(
                 'type' => 'Zend\Form\Element\Select',
                 'name' => 'carburant',
                 'options' => array(
                         'label' => 'Carburant',
                         'value_options' => array(

                                 '0' => 'Essence',
                                 '1' => 'Gasoil',
                                 '2' => 'Hybride',
         ),
         )
         ));
        $this->add(array(
            'type' => 'DoctrineModule\Form\Element\ObjectMultiCheckbox',
            'name' => 'option',
            'options' => array(
                'label' => 'Options Véhicule',
                'object_manager' => $this->getObjectManager(),
                'target_class'   => 'Vehicules\Entity\optionsvehicule',
                    'property'   => 'libellee',
                  )));   
        $this->add(array(
                'type' => 'DoctrineModule\Form\Element\ObjectSelect',
                'name' => 'categorie',
                'options' => array(
                        'label' => 'categorie',
                        'object_manager' => $this->getObjectManager(),
                'target_class'   => 'Vehicules\Entity\categorie',
                    'property'   => 'idcat',

                )
        ));
            $this->add(array(
                'type' => 'DoctrineModule\Form\Element\ObjectSelect',
                'name' => 'modele',
                'options' => array(
                        'label' => 'Modèle',
                        'object_manager' => $this->getObjectManager(),
                'target_class'   => 'Vehicules\Entity\modele',
                    'property'   => 'nom',
                )
        ));
        /*$this->add(array(
                'type' => 'DoctrineModule\Form\Element\ObjectSelect',
                'name' => 'modele',
                'options' => array(
                        'label' => 'Modèle',
                        'object_manager' => $this->getObjectManager(),
                        'target_class'   => 'Vehicules\Entity\modele',
                        'property'   => 'nom',
                        'is_method'      => true,
                        'find_method'    => array(
                                'name'   => 'findBy',
                                'params' => array(
                                        'criteria' => array('active' => 1),

                                        // Use key 'orderBy' if using ORM
                                        'orderBy'  => array('lastname' => 'ASC'),

                                        // Use key 'sort' if using ODM
                                        'sort'  => array('lastname' => 'ASC')
                                ),
                        ),
                ),
        ));*/
        $this->add(array(
                'type' => 'DoctrineModule\Form\Element\ObjectSelect',
                'name' => 'marque',
                'options' => array(
                        'label' => 'Marque',
                        'object_manager' => $this->getObjectManager(),
                        'target_class'   => 'Vehicules\Entity\marque',
                        'property'   => 'nom',
                )
        ));

        $this->add(array(
                'name' => 'dateMiseCirculation',
                'attributes' => array(
                        'type' => 'Zend\Form\Element\Date',
                ),
                'options' => array(
                        'label' => 'Date de Mise en Circulation',
                ),
        ));
        $this->add(array(
                'name' => 'numChasis',
                'attributes' => array(
                        'type' => 'text',
                ),
                'options' => array(
                        'label' => 'Numero de Chasis',
                ),
        ));
        $this->add(array(
                'name' => "Prix d'achat",
                'attributes' => array(
                        'type' => 'int',
                ),
                'options' => array(
                        'label' => "Prix d'achat",
                ),
        ));

        $this->add(array(
                'name' => 'concessionnaire',
                'attributes' => array(
                        'type' => 'text',
                ),
                'options' => array(
                        'label' => 'concessionnaire',
                ),
        ));


        $this->add(array(
                'name' => 'souslocation',
                'attributes' => array(
                        'type' => 'string',
                ),
                'options' => array(
                        'label' => 'Sous-location',
                ),
        )); 
        $this->add(array(
                'name' => 'remarque',
                'attributes' => array(
                        'type' => 'text',
                ),
                'options' => array(
                        'label' => 'remarque',
                ),
        )); 
        $this->add(array(
                'name' => 'puisfiscal',
                'attributes' => array(
                        'type' => 'int',
                ),
                'options' => array(
                        'label' => "puissance fiscale",
                ),
        ));
        $this->add(array(
                'type' => 'Zend\Form\Element\Select',
                'name' => 'nbreport',
                'options' => array(
                        'label' => 'Nombre de portes',
                        'value_options' => array(

                                '0' => '4',
                                '1' => '2',
                                '2' => '5',
                                '3' => '6',
                                '4' => '7',
                                '5' => '7',
                        ),
                )
        ));


        $this->add(array(
                'name' => 'dernierKm',
                'attributes' => array(
                        'type' => 'text',
                ),
                'options' => array(
                        'label' => 'Dernier  kilométrage',
                ),
        ));

        $this->add(array(
                'name' => 'submit',
                'attributes' => array(
                        'type' => 'submit',
                        'value' => 'Valider'
                ),
                ));
    }}

and this is my Entity Vehicule:

<?php

namespace Vehicules\Entity;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterInterface;
use Zend\InputFilter\Factory as InputFactory;
use Doctrine\ORM\Mapping as ORM;

/**
 * Vehicule
 *
 * @ORM\Table(name="vehicule", uniqueConstraints={@ORM\UniqueConstraint(name="VEHICULE_PK", columns={"idVeh"})}, indexes={@ORM\Index(name="ASSOCIATION11_FK", columns={"idCat"}), @ORM\Index(name="ASSOCIATION13_FK", columns={"idMod"})})
 * @ORM\Entity
 */
class Vehicule 
{     protected $inputFilter;

    /**
     * @var integer
     *
     * @ORM\Column(name="idVeh", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $idveh;

    /**
     * @var string
     *
     * @ORM\Column(name="matricule", type="string", length=254, nullable=false)
     */
    private $matricule;

    /**
     * @var string
     *
     * @ORM\Column(name="dateMiseCirculation", type="string", length=254, nullable=true)
     */
    private $datemisecirculation;

    /**
     * @var string
     *
     * @ORM\Column(name="numChasis", type="string", length=254, nullable=false)
     */
    private $numchasis;

    /**
     * @var string
     *
     * @ORM\Column(name="carburant", type="string", length=254, nullable=true)
     */
    private $carburant;

    /**
     * @var string
     *
     * @ORM\Column(name="dernierKm", type="decimal", precision=10, scale=0, nullable=false)
     */
    private $dernierkm;

    /**
     * @var integer
     *
     * @ORM\Column(name="prixachat", type="integer", precision=10, scale=0, nullable=false)
     */
    private $prixachat;

    /**
     * @var string
     *
     * @ORM\Column(name="concessionnaire", type="string", length=254, nullable=true)
     */
    private $concessionnaire;

    /**
     * @var integer
     *
     * @ORM\Column(name="sousLocation", type="smallint", nullable=true)
     */
    private $souslocation;

    /**
     * @var string
     *
     * @ORM\Column(name="remarque", type="string", length=254, nullable=true)
     */
    private $remarque;

    /**
     * @var integer
     *
     * @ORM\Column(name="puisFiscal", type="integer", nullable=true)
     */
    private $puisfiscal;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbrePort", type="integer", nullable=true)
     */
    private $nbreport;

    /**
     * @var \Vehicules\Entity\Categorie
     *
     * @ORM\ManyToOne(targetEntity="Vehicules\Entity\Categorie")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="idCat", referencedColumnName="idCat")
     * })
     */
    private $idcat;

    /**
     * @var \Vehicules\Entity\Modele
     *
     * @ORM\ManyToOne(targetEntity="Vehicules\Entity\Modele")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="idMod", referencedColumnName="idMod")
     * })
     */
    private $idmod;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Vehicules\Entity\Optionsvehicule", inversedBy="idveh")
     * @ORM\JoinTable(name="veh_option",
     *   joinColumns={
     *     @ORM\JoinColumn(name="idVeh", referencedColumnName="idVeh")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="idOptVeh", referencedColumnName="idOptVeh")
     *   }
     * )
     */
    private $idoptveh;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="Vehicules\Entity\Vehiculestatut", inversedBy="idveh")
     * @ORM\JoinTable(name="veh_status",
     *   joinColumns={
     *     @ORM\JoinColumn(name="idVeh", referencedColumnName="idVeh")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="idStatut", referencedColumnName="idStatut")
     *   }
     * )
     */
    private $idstatut;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->idoptveh = new \Doctrine\Common\Collections\ArrayCollection();
        $this->idstatut = new \Doctrine\Common\Collections\ArrayCollection();
    }


    /**
     * Get idveh
     *
     * @return integer 
     */
    public function getIdveh()
    {
        return $this->idveh;
    }

    /**
     * Set matricule
     *
     * @param string $matricule
     * @return Vehicule
     */
    public function setMatricule($matricule)
    {
        $this->matricule = $matricule;

        return $this;
    }

    /**
     * Get matricule
     *
     * @return string 
     */
    public function getMatricule()
    {
        return $this->matricule;
    }

    /**
     * Set datemisecirculation
     *
     * @param string $datemisecirculation
     * @return Vehicule
     */
    public function setDatemisecirculation($datemisecirculation)
    {
        $this->datemisecirculation = $datemisecirculation;

        return $this;
    }

    /**
     * Get datemisecirculation
     *
     * @return string 
     */
    public function getDatemisecirculation()
    {
        return $this->datemisecirculation;
    }

    /**
     * Set numchasis
     *
     * @param string $numchasis
     * @return Vehicule
     */
    public function setNumchasis($numchasis)
    {
        $this->numchasis = $numchasis;

        return $this;
    }

    /**
     * Get numchasis
     *
     * @return string 
     */
    public function getNumchasis()
    {
        return $this->numchasis;
    }

    /**
     * Set carburant
     *
     * @param string $carburant
     * @return Vehicule
     */
    public function setCarburant($carburant)
    {
        $this->carburant = $carburant;

        return $this;
    }

    /**
     * Get carburant
     *
     * @return string 
     */
    public function getCarburant()
    {
        return $this->carburant;
    }

    /**
     * Set dernierkm
     *
     * @param string $dernierkm
     * @return Vehicule
     */
    public function setDernierkm($dernierkm)
    {
        $this->dernierkm = $dernierkm;

        return $this;
    }

    /**
     * Get dernierkm
     *
     * @return string 
     */
    public function getDernierkm()
    {
        return $this->dernierkm;
    }

    /**
     * Set prixachat
     *
     * @param integer $prixachat
     * @return Vehicule
     */
    public function setPrixachat($prixachat)
    {
        $this->prixachat = $prixachat;

        return $this;
    }

    /**
     * Get prixachat
     *
     * @return integer
     */
    public function getPrixachat()
    {
        return $this->prixachat;
    }

    /**
     * Set concessionnaire
     *
     * @param string $concessionnaire
     * @return Vehicule
     */
    public function setConcessionnaire($concessionnaire)
    {
        $this->concessionnaire = $concessionnaire;

        return $this;
    }

    /**
     * Get concessionnaire
     *
     * @return string 
     */
    public function getConcessionnaire()
    {
        return $this->concessionnaire;
    }

    /**
     * Set souslocation
     *
     * @param integer $souslocation
     * @return Vehicule
     */
    public function setSouslocation($souslocation)
    {
        $this->souslocation = $souslocation;

        return $this;
    }

    /**
     * Get souslocation
     *
     * @return integer 
     */
    public function getSouslocation()
    {
        return $this->souslocation;
    }

    /**
     * Set remarque
     *
     * @param string $remarque
     * @return Vehicule
     */
    public function setRemarque($remarque)
    {
        $this->remarque = $remarque;

        return $this;
    }

    /**
     * Get remarque
     *
     * @return string 
     */
    public function getRemarque()
    {
        return $this->remarque;
    }

    /**
     * Set puisfiscal
     *
     * @param integer $puisfiscal
     * @return Vehicule
     */
    public function setPuisfiscal($puisfiscal)
    {
        $this->puisfiscal = $puisfiscal;

        return $this;
    }

    /**
     * Get puisfiscal
     *
     * @return integer 
     */
    public function getPuisfiscal()
    {
        return $this->puisfiscal;
    }

    /**
     * Set nbreport
     *
     * @param integer $nbreport
     * @return Vehicule
     */
    public function setNbreport($nbreport)
    {
        $this->nbreport = $nbreport;

        return $this;
    }

    /**
     * Get nbreport
     *
     * @return integer 
     */
    public function getNbreport()
    {
        return $this->nbreport;
    }

    /**
     * Set idcat
     *
     * @param \Vehicules\Entity\Categorie $idcat
     * @return Vehicule
     */
    public function setIdcat(\Vehicules\Entity\Categorie $idcat = null)
    {
        $this->idcat = $idcat;

        return $this;
    }

    /**
     * Get idcat
     *
     * @return \Vehicules\Entity\Categorie 
     */
    public function getIdcat()
    {
        return $this->idcat;
    }

    /**
     * Set idmod
     *
     * @param \Vehicules\Entity\Modele $idmod
     * @return Vehicule
     */
    public function setIdmod(\Vehicules\Entity\Modele $idmod = null)
    {
        $this->idmod = $idmod;

        return $this;
    }

    /**
     * Get idmod
     *
     * @return \Vehicules\Entity\Modele 
     */
    public function getIdmod()
    {
        return $this->idmod;
    }

    /**
     * Add idoptveh
     *
     * @param \Vehicules\Entity\Optionsvehicule $idoptveh
     * @return Vehicule
     */
    public function addIdoptveh(\Vehicules\Entity\Optionsvehicule $idoptveh)
    {
        $this->idoptveh[] = $idoptveh;

        return $this;
    }

    /**
     * Remove idoptveh
     *
     * @param \Vehicules\Entity\Optionsvehicule $idoptveh
     */
    public function removeIdoptveh(\Vehicules\Entity\Optionsvehicule $idoptveh)
    {
        $this->idoptveh->removeElement($idoptveh);
    }

    /**
     * Get idoptveh
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getIdoptveh()
    {
        return $this->idoptveh;
    }

    /**
     * Add idstatut
     *
     * @param \Vehicules\Entity\Vehiculestatut $idstatut
     * @return Vehicule
     */
    public function addIdstatut(\Vehicules\Entity\Vehiculestatut $idstatut)
    {
        $this->idstatut[] = $idstatut;

        return $this;
    }

    /**
     * Remove idstatut
     *
     * @param \Vehicules\Entity\Vehiculestatut $idstatut
     */
    public function removeIdstatut(\Vehicules\Entity\Vehiculestatut $idstatut)
    {
        $this->idstatut->removeElement($idstatut);
    }

    /**
     * Get idstatut
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getIdstatut()
    {
        return $this->idstatut;
    } 

    public function populate($data) {
        $this->setMatricule($data['matricule']) ;
        $this->setDatemisecirculation($data['dateMiseCirculation'])  ;
        $this->setNumchasis($data['numChasis']) ;
        $this->setCarburant($data['carburant']) ;
        $this->setDernierkm($data['dernierKm']) ;
        $this->setPrixachat($data["Prix d'achat"]) ;
        $this->setConcessionnaire($data['concessionnaire']) ;
        $this->setSouslocation($data['souslocation']) ;
        $this->setRemarque($data['remarque']) ;
        $this->setPuisfiscal($data['puisfiscal']) ;
        $this->setNbreport($data['nbreport']) ;
        //$this->addIdoptveh($data['option']) ; /* select................*/



        //$this->setIdmod() ; /* select................*/
        //$this->addIdstatut() ; /*ghanakhd l option dyal libre */

    }
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }

    public function getInputFilter()
    {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $factory = new InputFactory();
            $inputFilter->add($factory->createInput(array(
                    'name' => 'matricule',
                    'required' => true,
                    'filters' => array(
                            array('name' => 'StripTags'),
                            array('name' => 'StringTrim'),
                    ),
                    'validators' => array(
                            array(
                                    'name' => 'StringLength',
                                    'options' => array(
                                            'encoding' => 'UTF-8',
                                            'min' => 4,
                                            'max' => 14,
                                    ),
                            ),
                    ),
            )));
            $inputFilter->add($factory->createInput(array(
                    'name' => 'option',
                    'required' => false,

                    )));


            $this->inputFilter = $inputFilter;
            }

            return $this->inputFilter;
            }
            public function getArrayCopy()
            {
                return get_object_vars($this);
            }
}

this is my controller VehiculeController:

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/Vehicules for the canonical source repository
 * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 * 
 */

namespace Vehicules\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Vehicules\Form\VehiculeForm;
use Vehicules\Entity\Vehicule;
class VehiculesController extends AbstractActionController
{
    /**
     * @var Doctrine\ORM\EntityManager
     */
protected $_objectManager;
protected function getObjectManager()
{
    if (!$this->_objectManager) {
        $this->_objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
    }

    return $this->_objectManager;
}

    public function indexAction()
    {
        $vehicules = $this->getObjectManager()->getRepository('Vehicules\Entity\Vehicule')->findAll();
        return new ViewModel(array('vehicules' => $vehicules));
    }

    public function addAction()
    {   $_objectManager=$this->getObjectManager();
        $form = new VehiculeForm($_objectManager);

        $request = $this->getRequest();
        $post = $this->request->getPost();
        if ($this->request->isPost()) {
            $Vehicule= new Vehicule();
            $form->setData($post);
            $form->setInputFilter($Vehicule->getInputFilter());
            if ($form->isValid()) {
                $f=$form->getData();
                $Vehicule->populate($f);
                $cat = $this->getObjectManager()->getRepository('Vehicules\Entity\categorie')->findAll();
                foreach ($cat as $c){

                    if($c->getIdcat()==$f['categorie'] ){
                        $Vehicule->setIdcat($c) ;
                        exit;

                    }
                }
                $mod = $this->getObjectManager()->getRepository('Vehicules\Entity\modele')->findAll();
                foreach ($mod as $m){

                    if($m->getNom()==$f['modele'] ){
                        $Vehicule->setIdmod($m->getIdmod()) ;
                        exit;
                    }
                }

                $objectManager = $this->getObjectManager();
                $objectManager->persist($Vehicule);
                $objectManager->flush();
                $id=$Vehicule->getIdveh();
                var_dump($id);
                $viewModel = new ViewModel(array('form' =>$form,'donne'=>$id));
                return $viewModel;
            }
        }
        $viewModel = new ViewModel(array('form' =>$form));
        return $viewModel;

    }

    public function editAction()
    {

        $id = (int) $this->getEvent()->getRouteMatch()->getParam('id');
        if (!$id) {
            return $this->redirect()->toRoute('vehicules/default', array('controller'=>'vehicules','action'=>'add'));
        }
        $vehicule = $this->getObjectManager()->find('Vehicules\Entity\vehicule', $id);
        $objectManager= $this->getObjectManager();
        $form = new VehiculeForm($objectManager);
        $form->setBindOnValidate(false);
        $form->bind($vehicule);
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->post());
            if ($form->isValid()) {
                $form->bindValues();
                $this->getEntityManager()->flush();

                // Redirect to list of vehicules
                return $this->redirect()->toRoute('vehicules/default', array('controller'=>'vehicules','action'=>'index'));
            }
        }

        return array(
                'id' => $id,
                'form' => $form,
        );
    }
    public function deleteAction()
    {
        $id = (int)$this->getEvent()->getRouteMatch()->getParam('idVeh');
        if (!$id) {
            return $this->redirect()->toRoute('vehicules');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $del = $request->post()->get('del', 'No');
            if ($del == 'Yes') {
                $id = (int)$request->post()->get('id');
                $vehicule = $this->getEntityManager()->find('Vehicules\Entity\vehicule', $id);
                if ($vehicule) {
                    $this->getEntityManager()->remove($vehicule);
                    $this->getEntityManager()->flush();
                }
            }

            // Redirect to list of albums
            return $this->redirect()->toRoute('default', array(
                    'controller' => 'vehicules',
                    'action' => 'index',
            ));
        }

        return array(
                'id' => $id,
                'vehicule' => $this->getEntityManager()->find('Vehicules\Entity\vehicule', $id)->getArrayCopy()
        );
    }

}

to populate forgnein key idMod and idCat i tried with this:

$mod = $this->getObjectManager()->getRepository('Vehicules\Entity\modele')->findAll();
                foreach ($mod as $m){

                    if($m->getNom()==$f['modele'] ){
                        $Vehicule->setIdmod($m->getIdmod()) ;
                        exit;
                    }
                }

but id doesn't work :/

Hn develop
  • 17
  • 6
  • I have voted to close your question; simply because there is no question. You need to **clearly** explain the *problem* and what you are trying to accomplish rather than "it doesn't work" – AlexP May 29 '14 at 11:19
  • Sorry :/ i will edit it but please don't close it i really need your help – Hn develop May 29 '14 at 11:58
  • It's okay; I've read your code in a bit more detail and *think* I understand what you are trying to do. Not everyone will invest that much time in a question so my above comment is for your benefit really. – AlexP May 29 '14 at 12:05

1 Answers1

0

Your issue is the form/entity hydration. You don't need to reinvent the wheel here as Zend\Form already takes care of getting the data in and out of a form.

Currently your form uses the default ArraySerializable hydrator, so when the form is validated and you fetch the data (using $form->getData()) you are given an array. What you want is a already populated Vehicule entity.

The DoctrineModule\Stdlib\Hydrator\DoctrineObject is a hydrator specifically for Doctrine. If you attach it as the hydrator to your form it will return hydrated entity.

To solve this you need to STOP creating the form using new

$form = new VehiculeForm($_objectManager);

Instead create it via the ServiceManager

$form = $this->getServiceLocator()->get('MyModule\Form\VehiculeForm');

Now create the form from a service factory; allowing the injection of the form dependencies, including the hydrator.

MyModule/Factory/Form/VehiculeFormFactory.php

namespace MyModule\Factory\Form;

use MyModule\Entity;
use MyModule\Form;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
use DoctrineModule\Stdlib\Hydrator;

class VehiculeFormFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $sl)
    {
        $objectManager = $sl->get('Doctrine\ORM\EntityManager');

        $form = new Form\VehiculeForm($objectManager);
        $vehicule = new Entity\Vehicule();

        // create the hydrator; this could also be done via the
        // hydrator manager but create here for the example
        $hydrator = new DoctrineObject($objectManager);

        $form->setHydrator($hydrator);
        $form->setObject($vehicule);

        // We can also take care of the input filter here too!
        // meaning less code in the controller and only
        // one place to modify should it change
        $form->setInputFilter($Vehicule->getInputFilter());

        return $form;
    }
}

Module.php

public function getFormElementConfig()
{
    return array(
        'factories' => array(
            'MyModule\Form\VehiculeForm' => 'MyModule\Factory\Form\VehiculeForm' // path to our new factory
        ),
    );
}

You can now get rid of your populate() method and allot of the controller code.

FooController.php

//...
protected function getVehiculeForm()
{
    return $this->getServiceLocator()->get('MyModule\Form\VehiculeForm');
}

public function addAction()
{   
    $request = $this->getRequest();
    $form    = $this->getVehiculeForm();

    if ($request->isPost()) {

        $form->setData($request->getPost());

        if ($form->isValid()) {
            $vehicule = $form->getData(); // returns the entity!

            if ($vehicule instanceof Vehicule) {
                /// Fully hydrated entity!
                var_dump($vehicule);
            }
        } 
    }
    //...
}
//...
AlexP
  • 9,906
  • 1
  • 24
  • 43
  • can i use namespace MyModule\Form; without creating the new folder Factory ?? if not what's the important of it ? i have done all this but i got an error: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Vehicules\Form\VehiculeForm – Hn develop May 29 '14 at 15:44
  • public function populate($data) { $this->setMatricule($data['matricule'])... for exemple this line of populate function let doctrine to affect matricule of the form to Matricule of my entity but without this fuction how the hydrator can know that !!in our case we have the same name 'matricule' but sometimes we don't have the same names !! – Hn develop May 29 '14 at 17:46