Can't validate my form in Zend Framework 2 - php

So I create a form and I want to use it in my project. I use Zend Framework 2 and Doctrine Orm. The problem occurs when I submit the form: I had nothing, that means the form wasn't submitted. For more details I will write my code. So if someone has any solution I will be very appreciative.
This is my entity :
class Article implements InputFilterAwareInterface
{
protected $inputFilter;
/**
* #ORM\Column(name="publication", type="boolean")
*/
protected $publication;
public function __construct()
{
$this->date = new \Datetime();
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
protected $title;
// ....
/**
* Populate from an array.
*
* #param array $data
*/
// here maybe the data can't pass from my form to the entity !!
public function populate($data = array())
{
$this->content = $data['content'];
$this->title = $data['title'];
$this->date = $data['date'];
$this->publication = $data['publication'];
$this->image = $data['image'];
}
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' => 'content',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 60,
),
),
),
)));
// ....
}
}
Then my Action:
$form = new ArticleForm();
$form->get('submit')->setAttribute('label', 'Add');
$request = $this->getRequest();
if ($this->zfcUserAuthentication()->hasIdentity()) {
if ($request->isPost())
{
$article = new Article();
$form->setInputFilter($article->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$article->populate($form->getData());// here i think i have a problem
$this->getObjectManager()->flush();
$newId = $article->getId();
return $this->redirect()->toRoute('blog');
}
}
}

instead of : $article->populate($form->getData());
try: $article->populate($request->getPost()->toArray());//bad idea
or : $article->populate($form->getData()->toArray());//good idea
up:
$form->getData() will return entity so you must implement toArray() function;
public function toArray()
{
return array(
'title' => $this->title,
//...
);
}

Related

Php Dependency Injecttion in Zend 2

I have two classes. Lets says it is Album and AlbumManager. Album is a intake class which I am using for generating basic entity function. I do not want to touch Album for custom functions. All other custom function I wrote in AlbumManager class.
Now from controller, when I try to access Album class through AlbumManager, it through me an error:
Can not be mapped or accessed.
How can I handle this type of dependency? Here are the classes:
Album.php
<?php
namespace Album\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Album
*
* #ORM\Table(name="album")
* #ORM\Entity
*/
class Album
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="artist", type="string", length=255, precision=0, scale=0, nullable=false, unique=false)
*/
private $artist;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set artist
*
* #param string $artist
* #return Album
*/
public function setArtist($artist)
{
$this->artist = $artist;
return $this;
}
/**
* Get artist
*
* #return string
*/
public function getArtist()
{
return $this->artist;
}
?>
AlbumManager.php
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
namespace Album\Manager;
use Album\Entity as Album;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterInterface;
class AlbumManager
{
private $album;
protected $inputFilter;
public function __construct(Album\Entity $album)
{
$this->album = $album;
}
public function getAlbum()
{
return $this->album;
}
/**
* Magic getter to expose protected properties.
*
* #param string $property
* #return mixed
*/
public function __get($property)
{
return $this->$property;
}
/**
* Magic setter to save protected properties.
*
* #param string $property
* #param mixed $value
*/
public function __set($property, $value)
{
$this->$property = $value;
}
/**
* Convert the object to an array.
*
* #return array
*/
public function getArrayCopy()
{
return get_object_vars($this);
}
/**
* Populate from an array.
*
* #param array $data
*/
public function populate($data = array())
{
$this->album->setId($data['id']);
$this->album->setArtist($data['artist']);
$this->album->setTitle($data['title']);
}
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' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'artist',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'title',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
AlbumController.php
<?php
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController,
Zend\View\Model\ViewModel,
Album\Form\AlbumForm,
Doctrine\ORM\EntityManager,
Doctrine\ORM\EntityRepository,
Album\Entity\Album,
Album\Manager\AlbumManager,
class AlbumController extends AbstractActionController
{
public function addAction()
{
$form = new AlbumForm();
$form->get('submit')->setAttribute('label', 'Add');
$request = $this->getRequest();
if ($request->isPost()) {
$album = new Album();
$albumManager = new AlbumManager($album);
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$album->populate($form->getData());
$this->getEntityManager()->persist($album);
$this->getEntityManager()->flush();
// Redirect to list of albums
return $this->redirect()->toRoute('album');
}
}
return array('form' => $form);
}
?>
See the code at AlbumController
$album = new Album();
$albumManager = new AlbumManager($album);
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$album->populate($form->getData());
The album object can not get access to the getInputFilter and populate function which I write down in the Album Repository. I understood this happened because of the dependency injected. But what would be the solution so that I can access the album object, set the form data and also can use the album manger functions?

addAction,editAction zend framework2 doctrine2

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 :/
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);
}
}
}
//...
}
//...

How to validate Checkbox in Zend Framework 2?

So what i want is to validate my Checkbox in my form and check if it's checked so i should save it as 1 in my database else as 0, like this :
$this->add(array(
'name' => 'publication',
'type' => 'Zend\Form\Element\Checkbox',
'options' => array(
'checked_value' => 1,
'unchecked_value' => 0,
),
));
But when i tried i got Null in my database !!, for more details i will write some of my codes,
This is my view :
<label>Publication:</label>
<?php
echo $this->formInput($form->get('publication'));
?>
And this is my Entity :
/**
* #ORM\Column(name="publication", type="boolean")
*/
protected $publication;
/**
* Set publication
*
* #param boolean $publication
* #return Article
*/
public function setPublication($publication)
{
$this->publication = $publication;
return $this;
}
/**
* Get publication
*
* #return boolean
*/
public function getPublication()
{
return $this->publication;
}
public function exchangeArray($data)
{
$this->publication = (isset($data['publication'])) ? $data['publication'] : null;
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'publication',
'required' => false,
));
So please if someone has any solution i will be so appreciative :)
When a checkbox is not ticked, it is not included in the post. In your exchangeArray, you are setting it null in this case.

ZF2: FieldSet getInputFilterSpecification() gets called twice

getInputFilterSpecification() read twice for a fieldset when used with fileprg Controller plugin.
Basically I have a simple form with a single fieldset:
The Form:
class CreateEditReward extends ProvideEventsForm
{
public function __construct($name = null, $options = array())
{
parent::__construct($name ?: 'Reward', $options);
$this->add(array(
'name' => 'submit',
'type' => 'submit'
));
$this->add(array(
'name' => 'cancel',
'type' => 'button'
));
}
public function init()
{
parent::init();
$this->add(array(
'name' => 'reward',
'type' => 'MyAchievement\Form\RewardFieldset',
'options' => array(
'use_as_base_fieldset' => true
)
));
if (($listener = $this->get('reward')) instanceof ListenerAggregateInterface) {
/** #var $listener ListenerAggregateInterface */
$this->getEventManager()->attachAggregate($listener);
}
}
}
The form extends the most basic EventsCapable implmentation and is not related to the problem.
The Fieldset:
class RewardFieldset extends Fieldset implements
InputFilterProviderInterface,
ListenerAggregateInterface
{
/**
* #var RewardService
*/
protected $rewardService;
/**
* #var WebPathResolver
*/
protected $webPathResolver;
protected $listeners = array();
public function __construct(RewardService $rewardService, WebPathResolver $webPathResolver, $name = null, $options = array())
{
parent::__construct($name ?: 'Reward', $options);
$this->rewardService = $rewardService;
$this->webPathResolver = $webPathResolver;
//...
$this->add(array(
'name' => 'thumb',
'type' => 'file',
'options' => array(
'label' => 'Thumb'
),
'attributes' => array(
'id' => 'thumb',
'data-rel' => null
)
));
// .. more elts
}
/**
* Should return an array specification compatible with
* {#link Zend\InputFilter\Factory::createInputFilter()}.
*
* #return array
*/
public function getInputFilterSpecification()
{
return array(
// ... other elts input filters
'thumb' => array(
'required' => false,
'filters' => array(
array(
'name' => 'fileRenameUpload',
'options' => array(
'target' => './data/upload',
'overwrite' => true,
'randomize' => true,
'use_upload_name' => true
)
)
),
'validators' => array(
array(
'name' => 'fileMimeType',
'options' => array(
'image',
'enableHeaderCheck' => true
)
)
)
)
);
}
public function addThumbPreview(FormEvent $e)
{
/** #var $object Reward */
if (! ($object = $e->getObject()) instanceof Reward) {
return;
}
if ($object->getThumb()) {
$this->get('thumb')
->setAttribute('data-rel', $this->webPathResolver->getPath($object, $object->getThumb()));
}
}
/**
* Attach one or more listeners
*
* Implementors may add an optional $priority argument; the Eve\ntManager
* implementation will pass this to the aggregate.
*
* #param EventManagerInterface $events
*
* #return void
*/
public function attach(EventManagerInterface $events)
{
$this->listeners[] = $events->attach(FormEvent::EVENT_POST_BIND, array($this, 'addThumbPreview'));
}
/**
* Detach all previously attached listeners
*
* #param EventManagerInterface $events
*
* #return void
*/
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $i => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$i]);
}
}
}
}
My controller's edit action:
public function editAction()
{
/** #var $request Request */
$request = $this->getRequest();
$back = $request->getQuery('back', $this->url()->fromRoute('admin/reward'));
/** #var $reward Reward */
if (null === $reward = $this->rewardService->fetchById($id = $this->params()->fromRoute('id'))) {
return $this->redirect()->toUrl($back);
}
$form = $this->getCreateEditForm();
$form->bind($reward);
if (($prg = $this->fileprg($form)) instanceof ResponseInterface) {
return $prg;
}
if (is_array($prg)) {
try {
if ($form->isValid()) {
$this->rewardService->updateReward($reward);
$this->flashMessenger()->addSuccessMessage('Changes saved');
$this->redirect()->toRoute('admin/reward',
array('action' => 'edit', 'id' => $id),
array('query' => array('back' => $back)));
} else {
/** #var $rewardFieldset FieldsetInterface */
$rewardFieldset = $form->get('reward');
/** #var $thumbElt ElementInterface */
$thumbElt = $rewardFieldset->get('thumb');
if (! $thumbElt->getMessages()) {
$reward->setThumb($thumbElt->getValue());
$this->rewardService->updateReward($reward);
}
}
} catch (\Exception $e) {
$this->flashMessenger()->addErrorMessage('Changes could not be saved');
return $this->redirect()->toUrl($back);
}
}
return new ViewModel(array(
'form' => $form,
'reward' => $reward,
'back' => $back
));
}
My module conf for the form:
/**
* Expected to return \Zend\ServiceManager\Config object or array to
* seed such an object.
*
* #return array|\Zend\ServiceManager\Config
*/
public function getFormElementConfig()
{
return array(
'invokables' => array(
'MyAchievement\Form\CreateEditReward' => 'MyAchievement\Form\CreateEditReward',
),
'factories' => array(
'MyAchievement\Form\RewardFieldset' => function (FormElementManager $fm) {
/** #var $rewardService RewardService */
$rewardService = $fm->getServiceLocator()->get('MyAchievement\Service\Reward');
/** #var $webPathResolver WebPathResolver */
$webPathResolver = $fm->getServiceLocator()->get('Application\Service\WebPathResolver');
$fieldset = new RewardFieldset($rewardService, $webPathResolver);
$fieldset->setHydrator(new ClassMethods());
return $fieldset;
}
)
);
}
The problem is the getInputFilterSpecifications() is called twice, thus everytime I try to upload a picture with my form I get
Zend\Filter\Exception\RuntimeException:
File './data/upload/my-thumb_5249d42bd582b.jpg' could not be renamed. An error occurred while processing the file.
That is because my filters run twice on the same thumbnail, the first time it is successful (I can even see the file uploaded to the temp dir).
Thanks.

Unrecognized field: user_name, while querying Via Doctrine using ZF2

here is the snippet to my code when i try to query it like this
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
//check authentication...
$this->getAuthService()->getAdapter()
->setIdentity($request->getPost('username'))
->setCredential($request->getPost('password'));
$username = $request->getPost('username');
$password = $request->getPost('password');
$result = $this->getAuthService()->authenticate();
$criteria = array("user_name" => $username,);
$results= $this->getEntityManager()->getRepository('Subject\Entity\User')->findBy($criteria);
print_r($results);
exit;
i get the following error
Unrecognized field: user_name
These are my includes
Use Doctrine\ORM\EntityManager,
Album\Entity\Album;
Edit: this is my Subject\Entity\User file
<?php
namespace Subject\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\Factory as InputFactory;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
/**
* #ORM\Entity
* #ORM\Table(name="users")
* #property string $username
* #property string $password
* #property int $id
*/
class User implements InputFilterAwareInterface {
protected $_username;
protected $_password;
/**
* #ORM\OneToMany(targetEntity="Subject\Entity\Subject", mappedBy="user")
* #var Collection
*/
private $subjects;
/** #ORM\Id() #ORM\Column(type="integer") #ORM\GeneratedValue(strategy="AUTO") #var int */
protected $_id;
public function __get($property) {
return $this->$property;
}
public function __set($property, $value) {
$this->$property = $value;
}
//Getters and setters
/** #return Collection */
public function getSubjects() {
return $this->subjects;
}
/** #param Comment $comment */
public function addSubject(Subject $subjects) {
$this->subjects->add($subjects);
$subjects->setUser($this);
}
public function __construct($subjects) {
//Initializing collection. Doctrine recognizes Collections, not arrays!
$this->subjects = new ArrayCollection();
}
public function getArrayCopy() {
return get_object_vars($this);
}
public function populate($data = array()) {
$this->_id = $data['id'];
$this->_username = $data['username'];
$this->_password = $data['password'];
}
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' => 'id',
'required' => true,
'filters' => array(
array('name' => 'Int'),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'username',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$inputFilter->add($factory->createInput(array(
'name' => 'password',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
//put your code here
}
?>
You are querying for the wrong field. The field is named _username in your entity class. Also check you annotations, _username and _password seem to not have any so they won't be created as database fields.
If you set up your entity correctly and all fields are in database you just need to query for your _username property:
if ($request->isPost()) {
$form->setData($request->getPost());
$repo = $this->getEntityManager()->getRepository('Subject\Entity\User');
if ($form->isValid()) {
// snip ...
$criteria = array("_username" => $username,);
$results= $repo->findBy($criteria);
print_r($results);
exit;
}
}
You user entity should look something like:
class User implements InputFilterAwareInterface {
/**
* #ORM\Column(name="username", type="string", length=64, unique=true)
*/
protected $_username;
/**
* #ORM\Column(name="password", type="string", length=64)
*/
protected $_password;
// snip ...
}
You may take a look at the PSR-2 standards. Underscores in method and variable names are discouraged by now.

Categories