Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fabiocarneiro/7252844 to your computer and use it in GitHub Desktop.
Save fabiocarneiro/7252844 to your computer and use it in GitHub Desktop.
<?php
use Zend\Form\Fieldset;
use Zend\Form\Form;
use Zend\Form\View\Helper\Form as FormHelper;
use Zend\Form\View\HelperConfig;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\Hydrator\ObjectProperty;
use Zend\View\Renderer\PhpRenderer;
include 'vendor/autoload.php';
class Entity
{
public $property;
public function __construct($property = null)
{
$this->property = $property;
}
}
$form = new Form();
$form->getFormFactory()->getFormElementManager()->setFactory('EntityFieldset', function(){
$entityFieldset = new Fieldset();
$entityFieldset->add(array(
'name' => 'property',
'type' => 'text'
));
$entityFieldset->setHydrator(new ObjectProperty());
$entityFieldset->setObject(new Entity());
return $entityFieldset;
});
$form->add(array(
'name' => 'entities',
'type' => 'collection',
'options' => array(
'allow_add' => true,
'create_new_objects' => true,
'target_element' => array(
'type' => 'EntityFieldset',
),
),
));
/*****************/
// POST simulation
$object = new ArrayObject(array('entities'));
$form->bind($object);
$form->setData(array(
'entities' => array(
array('property' => 'foo'),
array('property' => 'bar'),
)
));
if ($form->isValid()) {
var_dump(ArrayUtils::iteratorToArray($object));
};
/**
* output:
*
* array(1) {
* 'entities' =>
* array(2) {
* [0] =>
* class Entity#28 (1) {
* public $property =>
* string(3) "foo"
* }
* [1] =>
* class Entity#40 (1) {
* public $property =>
* string(3) "bar"
* }
* }
* }
*
/*************/
/*****************/
// GET simulation
$object = new ArrayObject(array(
'entities' => array(
new Entity('foo'),
new Entity('bar'),
new Entity('baz'),
)
));
$form->bind($object);
$view = new PhpRenderer();
$config = new HelperConfig();
$config->configureServiceManager($view->getHelperPluginManager());
$formHelper = new FormHelper();
$formHelper->setView($view);
echo $formHelper->render($form);
/**
* output:
* <form action="" method="POST">
* <input type="text" name="entities[0][property]" value="foo">
* <input type="text" name="entities[1][property]" value="bar">
* <input type="text" name="entities[2][property]" value="baz">
* </form>
*
/*************/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment