我使用zendframework 2和doctrine 2。我的addAction不工作,我没有任何错误,但当我有效的形式没有行创建在我的数据库!!我想我在输入外键时有问题!这是我的表单:
<?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'
),
));
}}
,这是我的实体车辆规则:
<?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);
}
}
这是我的控制器:
<?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()
);
}
}
填充外键idMod和idCat我试过了:
$mod = $this->getObjectManager()->getRepository('Vehicules'Entity'modele')->findAll();
foreach ($mod as $m){
if($m->getNom()==$f['modele'] ){
$Vehicule->setIdmod($m->getIdmod()) ;
exit;
}
}
但id不工作:/
您的问题是形式/实体水合作用。您不需要在这里重新发明轮子,因为Zend'Form
已经负责将数据输入和取出表单。
目前您的表单使用默认的ArraySerializable
水合器,所以当表单被验证并获取数据(使用$form->getData()
)时,您将获得array
。您需要的是一个已经填充的Vehicule
实体。
DoctrineModule'Stdlib'Hydrator'DoctrineObject
是专门为Doctrine设计的水合剂。如果您将其作为水合剂附加到表单上,它将返回水合实体。
要解决这个问题,您需要STOP使用new
$form = new VehiculeForm($_objectManager);
通过ServiceManager
创建它$form = $this->getServiceLocator()->get('MyModule'Form'VehiculeForm');
现在从服务工厂创建表单;允许注入表单依赖项,包括水合器。
MyModule里/工厂/形式/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
),
);
}
你现在可以摆脱你的populate()
方法和分配控制器代码。
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);
}
}
}
//...
}
//...