Skip to content

Instantly share code, notes, and snippets.

@fabiopaiva
Last active August 29, 2015 14:06
Show Gist options
  • Save fabiopaiva/c8e725573fa6f8832f76 to your computer and use it in GitHub Desktop.
Save fabiopaiva/c8e725573fa6f8832f76 to your computer and use it in GitHub Desktop.
ZF2 + Doctrine + Form example
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Application\Form\MyForm;
class MyController extends AbstractActionController {
public function newAction(){
$form = new MyForm('nameMyForm',
array(
'em' => $this->getServiceLocator()
->get('Doctrine\ORM\EntityManager')
)
);
$form->prepare();
return array(
'form' => $form
);
}
}
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
*/
class MyEntity {
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Application\Entity\SomeEntity")
* @var SomeEntity
*/
protected $mySelect;
//getters and setters must be created here
}
<?php
namespace Application\Form;
use Zend\Form\Form;
use Application\Entity\MyEntity;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject;
class MyForm extends Form{
public function __construct($name,$options = array()){
parent::__construct($name,$options);
//set object, hydrator and add input fields here
$this
->setObject(new MyEntity())
->setHydrator(new DoctrineObject($options['em'])
->add(array(
'type' => 'hidden',
'name' => 'id'
))
->add(
array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'mySelect',
'options' => array(
'object_manager' => $options['em'],
'target_class' => 'Application\Entity\SomeEntity',
'property' => 'name',
),
)
);
}
}
<h1>Form</h1>
<?php echo $this->form()->openTag($form);?>
<?php echo $this->formCollection($form);?>
<?php echo $this->form()->closeTag($form);?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment