1

如果我使用ZF2和Doctrine开发一个项目,该对象具有与Doctrine hydrator tutorial类似的多对多关系,则父字段集将显示像这样:如何在ZF2和Doctrine中以多对一的关系引用子元素

namespace Application\Form; 

use Application\Entity\BlogPost; 
use Doctrine\Common\Persistence\ObjectManager; 
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator; 
use Zend\Form\Fieldset; 
use Zend\InputFilter\InputFilterProviderInterface; 

class BlogPostFieldset extends Fieldset implements InputFilterProviderInterface 
{ 
    public function __construct(ObjectManager $objectManager) 
    { 
     parent::__construct('blog-post'); 

     $this->setHydrator(new DoctrineHydrator($objectManager)) 
      ->setObject(new BlogPost()); 

     $this->add(array(
      'type' => 'Zend\Form\Element\Text', 
      'name' => 'title' 
     )); 

     $tagFieldset = new TagFieldset($objectManager); 
     $this->add(array(
      'type' => 'Zend\Form\Element\Collection', 
      'name' => 'tags', 
      'options' => array(
       'count'   => 2, 
       'target_element' => $tagFieldset 
      ) 
     )); 
    } 

    public function getInputFilterSpecification() 
    { 
     return array(
      'title' => array(
       'required' => true 
      ), 
     ); 
    } 
} 

和形式要素可以在这样的视图访问:

// edit.phtml: 

// ... 

$bpfs=$form->get('blog-post'); 
$tfss=$bpfs->get('tags')->getFieldsets(); 
$tfs=$tfss[0]; 

$tagName = $tfs->get('name'); 

// ... 

但是,如果我想使用多到一的关系,我不知道怎么样编码子元素。在BlogPost Fieldset中,我认为tag元素不再是一个集合,因为只有其中的一个。然而,标签仍然是一个字段,所以我想它进入BlogPost Fieldset这样的:

$tagFieldset = new TagFieldset($objectManager); 
$this->add(array(
    'name' => 'tag', 
    'options' => array(
     'target_element' => $tagFieldset 
    ) 
)); 

(这是一个单独的记录,所以我改名为tag这不是一个集合,也没有。它似乎是任何其他形式的ZF2元素,所以我放弃了type属性语句)

然后在视图中,我试图访问表单元素是这样的:

// edit.phtml: 

// ... 

$bpfs=$form->get('blog-post'); 
$tfs=$bpfs->get('tag')->getFieldsets(); 

$tagName = $tfs->get('name'); 

// ... 

但是这给错误,

Fatal error: Call to undefined method Zend\Form\Element::getFieldsets() in … 

这应该如何编码?

回答

1

由于tag只是一个字段集,你应该这样做:

​​
相关问题