Reputation: 1246
If I develop a project using ZF2 and Doctrine that hydrates an object with a Many-to-Many relationship similar this Doctrine hydrator tutorial, the parent fieldset would look like this:
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
),
);
}
}
and the form elements could be accessed in the view like this:
// edit.phtml:
// ...
$bpfs=$form->get('blog-post');
$tfss=$bpfs->get('tags')->getFieldsets();
$tfs=$tfss[0];
$tagName = $tfs->get('name');
// ...
However, if I want to use Many-to-One relationship, I'm not sure how to code the child elements. In the BlogPost Fieldset
, I assume that the tag
element is no longer a collection because there will only be one of them. Yet the tag is still a fieldset, so I guess that it goes into the BlogPost Fieldset
like this:
$tagFieldset = new TagFieldset($objectManager);
$this->add(array(
'name' => 'tag',
'options' => array(
'target_element' => $tagFieldset
)
));
(It's a single record, so I've changed the name to tag
. It's not a collection, nor does it seem to be any other ZF2 form elements, so I've dropped the type
attribute statement.)
Then in the view, I attempt to access the form elements like this:
// edit.phtml:
// ...
$bpfs=$form->get('blog-post');
$tfs=$bpfs->get('tag')->getFieldsets();
$tagName = $tfs->get('name');
// ...
but this gives the error,
Fatal error: Call to undefined method Zend\Form\Element::getFieldsets() in …
How should this be coded properly?
Upvotes: 1
Views: 121
Reputation: 2507
Since tag
is just one fieldset, you should do this:
$tfs=$bpfs->get('tag');
$tagName = $tfs->get('name');
Upvotes: 1