ZF2 + Doctrine2:以zend形式验证“一对多”关联的集合字段时出错

时间:2014-04-07 22:48:29

标签: forms validation doctrine-orm zend-framework2 associations

在此之前,感谢阅读并抱歉我的英语。

实体:

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();
     }   

协会类型: Morfologia - >一对多 - > 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.

     //(...)

控制器

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);
}

查看

<?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>

当控制器验证表格时:

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

我收到以下错误: 教义\ DBAL \ DBALException

档案馆:

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: «»

堆栈追踪:

#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}

我尝试用params选择* FROM patrimonio t0 WHERE t0.id [&#34;&#34;]

如何避免此错误? 如何在没有任何相关Patrimonio的情况下注册新实体Morfologia并且不会收到此错误?

1 个答案:

答案 0 :(得分:0)

我发现了问题:

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
}

最后从表单

获取morfologia对象实例
if ($form->isValid()){
    $morfologia = $form->getData(); 

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

    //some code
}

并且morfologia正确刷新了!