ZF2 + Doctrine2: Error when validate a collection field of an One To Many association in zend form

Before anything else, thanks for read and sorry for my english.

Entities:

Morfologia

namespace Content\Entity;

/** 
 * Morfologia
 * 
 * @ORM\Entity 
 * @ORM\Table(name="morfologia")
 * @Annotation\Name("morfologia")
 * @Annotation\Hydrator("Zend\Stdlib\Hydrator\ObjectProperty")
 */

class Morfologia
 {
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     * @Annotation\Type("Zend\Form\Element\Hidden")
     */
     private $id;

     /** @ORM\Column(type="string") 
      * @Annotation\Type("Zend\Form\Element\Text")
      * @Annotation\Filter({"name":"StripTags"})
      * @Annotation\Filter({"name":"StringTrim"})
      * @Annotation\Validator({"name":"Alnum", "options": {"allowWhiteSpace":"true"}})
      * @Annotation\Validator({"name":"StringLength", "options": {"min":"2", "max":"250"}})
      * @Annotation\Options({"label":"Nombre: "})    
      * */
     private $nombre;

     /** @ORM\Column(type="text") 
      * @Annotation\Type("Zend\Form\Element\Textarea")
      * @Annotation\Filter({"name":"StripTags"})
      * @Annotation\Filter({"name":"StringTrim"})
      * @Annotation\Validator({"name":"Alnum", "options": {"allowWhiteSpace":"true"}})
      * @Annotation\Options({"label":"Descripcion: "}) 
      * */
     private $descripcion; //texto descriptivo

     //(...)

     /**
      * 
      * @ORM\OneToMany(targetEntity="Patrimonio", mappedBy="tipo_morfo")
      * @var Patrimonio[]
      */
     private $patrimonios;

     public function __construct()
     {
        $this->patrimonios = new ArrayCollection();
     }   

Type of association: Morfologia -> One to Many -> Patrimonios

Patrimonio

/** 
 * Patrimonio
 * 
 * @ORM\Entity 
 * @ORM\Table(name="patrimonio")
 * 
 */

 class Patrimonio //implements InputFilterAwareInterface
 {  
    /**
     * @var integer $id
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\Column(name="id", type="integer", nullable=false)
     */
     private $id;

     /*Propios del patrimonio*/

     /** @ORM\Column(type="string") */
     private $nombre;

     /** @ORM\Column(type="text") */
     private $descripcion; //texto descriptivo

     (...)

     /** @ORM\ManyToOne(targetEntity="Morfologia", inversedBy="patrimonios")
      *  @ORM\JoinColumn(nullable=true) */
     private $tipo_morfo; //tip. morfológico: pirámide, etc.

     //(...)

Controller

public function addAction()
{
    $builder = new DoctrineAnnotationBuilder($this->getObjectManager());
    $form    = $builder->createForm('Content\Entity\Morfologia');

    $btnReg = new Element('send');
    $btnReg->setValue('Registrar');
    $btnReg->setAttributes(array(
        'type'  => 'submit'
    ));
    $form->add($btnReg);

    $form->setHydrator(new DoctrineHydrator($this->getObjectManager(),'Content\Entity\Morfologia'));

    $request = $this->getRequest();
    if ($request->isPost()){
        $morfologia = new Content\Entity\Morfologia();
        $form->bind($morfologia);
        $form->setData($request->getPost());

        if ($form->isValid()){
            $morfologia->exchangeArray($form->getData());

            $this->getObjectManager()->persist($morfologia);
            $this->getObjectManager()->flush();

            return $this->redirect()->toRoute('content', array(
                'controller' => 'morfologia', 
                'action' => 'index'
            ));                         
        }
    }
    return array('form' => $form);
}

View

<?php
$form = $this->form;

$form->setAttribute('action', $this->url('content', array('controller' => 'morfologia', 'action' => 'add')));
$form->prepare();

echo $this->form()->openTag($form);
    echo $this->formCollection($form);
echo $this->form()->closeTag();
?>
</div>

When the controller validate the form:

if ($form->isValid()){
  //...
}

I get the following error: Doctrine\DBAL\DBALException

Archivo:

C:\xampp\htdocs\culturart\php\vendor\doctrine\dbal\lib\Doctrine\DBAL\DBALException.php:91

Mensaje:

An exception occurred while executing 'SELECT t0.id AS id1, t0.nombre AS nombre2, t0.descripcion AS descripcion3, t0.historia_breve AS historia_breve4, t0.extension AS extension5, t0.lat AS lat6, t0.lon AS lon7, t0.alt AS alt8, t0.perimetro AS perimetro9, t0.ubica_geo AS ubica_geo10, t0.medios_acceso AS medios_acceso11, t0.tipo_crono_id AS tipo_crono_id12, t0.tipo_morfo_id AS tipo_morfo_id13, t0.epoca_id AS epoca_id14, t0.cultura_id AS cultura_id15, t0.ubica_politica_id AS ubica_politica_id16, t0.img_superpuesta_id AS img_superpuesta_id17, t0.modelo_3d_id AS modelo_3d_id18 FROM patrimonio t0 WHERE t0.id = ?' with params [""]:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: «»

Stack trace:

#0 app\vendor\doctrine\dbal\lib\Doctrine\DBAL\Connection.php(702): Doctrine\DBAL\DBALException::driverExceptionDuringQuery(Object(PDOException), 'SELECT t0.id AS...', Array)
#1 app\vendor\doctrine\orm\lib\Doctrine\ORM\Persisters\BasicEntityPersister.php(748): Doctrine\DBAL\Connection->executeQuery('SELECT t0.id AS...', Array, Array)
#2 app\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php(460): Doctrine\ORM\Persisters\BasicEntityPersister->load(Array)
#3 app\vendor\doctrine\doctrine-module\src\DoctrineModule\Stdlib\Hydrator\DoctrineObject.php(433): Doctrine\ORM\EntityManager->find('Content\Entity\...', '')
#4 app\vendor\doctrine\doctrine-module\src\DoctrineModule\Stdlib\Hydrator\DoctrineObject.php(366): DoctrineModule\Stdlib\Hydrator\DoctrineObject->find('', 'Content\Entity\...')
#5 app\vendor\doctrine\doctrine-module\src\DoctrineModule\Stdlib\Hydrator\DoctrineObject.php(239): DoctrineModule\Stdlib\Hydrator\DoctrineObject->toMany(Object(Content\Entity\Morfologia), 'patrimonios', 'Content\Entity\...', '')
#6 app\vendor\doctrine\doctrine-module\src\DoctrineModule\Stdlib\Hydrator\DoctrineObject.php(107): DoctrineModule\Stdlib\Hydrator\DoctrineObject->hydrateByValue(Array, Object(Content\Entity\Morfologia))
#7 app\vendor\zendframework\zendframework\library\Zend\Form\Fieldset.php(546): DoctrineModule\Stdlib\Hydrator\DoctrineObject->hydrate(Array, Object(Content\Entity\Morfologia))
#8 app\vendor\zendframework\zendframework\library\Zend\Form\Form.php(364): Zend\Form\Fieldset->bindValues(Array)
#9 app\vendor\zendframework\zendframework\library\Zend\Form\Form.php(513): Zend\Form\Form->bindValues()
#10 app\module\Content\src\Content\Controller\MorfologiaController.php(71): Zend\Form\Form->isValid()
#11 app\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractActionController.php(83): Content\Controller\MorfologiaController->addAction()
#12 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#13 app\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#14 app\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#15 app\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractController.php(117): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#16 app\vendor\zendframework\zendframework\library\Zend\Mvc\DispatchListener.php(114): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#17 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#18 app\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#19 app\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#20 app\vendor\zendframework\zendframework\library\Zend\Mvc\Application.php(309): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#21 app\public\index.php(26): Zend\Mvc\Application->run()
#22 {main}

I tried to Select * FROM patrimonio t0 WHERE t0.id with params [""]

How can I avoid this error? How can I register a new entity Morfologia without any associated Patrimonio and don't get this error?

Answers


I have found the problem:

public function addAction()
{
    $builder = new DoctrineAnnotationBuilder($this->getObjectManager());
    $form    = $builder->createForm('Content\Entity\Morfologia');

    //some code

    $form->remove('patrimonios'); //I should have removed the collection field from the form

    ///some code
}

Finally get the morfologia object instance from form

if ($form->isValid()){
    $morfologia = $form->getData(); 

    $this->getObjectManager()->persist($morfologia);
    $this->getObjectManager()->flush();

    //some code
}

And the morfologia was flushed correctly!


Need Your Help

Using Linq-to-SQL preload without joins

linq-to-sql eager-loading

Like many people, I am trying to squeeze the best performance out of my app while keeping the code simple and readable as possible. I am using Linq-to-SQL and am really trying to keep my data layer...