Skip to content

Instantly share code, notes, and snippets.

@maglnet
Last active July 10, 2017 10:49
Show Gist options
  • Save maglnet/be6966e397237b4c38a3729ff4c04403 to your computer and use it in GitHub Desktop.
Save maglnet/be6966e397237b4c38a3729ff4c04403 to your computer and use it in GitHub Desktop.
UUID / Doctrine / ObjectSelect
<?php
$hydrator = new DoctrineObject($this->em, true);
$hydrator->addStrategy('parentFoo', new UUIDFromObjectStrategy());
$form = new FooForm($this->em);
$form->setHydrator($hydrator);
$form->bind($group);
<?php
use Doctrine\ORM\EntityManager;
use Zend\Form\Form;
class FooForm extends Form
{
/**
* @var EntityManager
*/
private $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
// we want to ignore the name passed
parent::__construct('Foo');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'name',
'type' => 'Text',
'options' => array(
'label' => 'Name',
),
));
$this->add(array(
'type' => '\DoctrineModule\Form\Element\ObjectSelect',
'name' => 'parentFoo',
'options' => array(
'empty_option' => '--- please select ---',
'label' => 'What?',
'object_manager' => $this->em,
'target_class' => 'My\Foo',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Save',
'id' => 'submitbutton',
),
));
}
}
<?php
use Ramsey\Uuid\Uuid;
use Zend\Stdlib\Hydrator\Strategy\StrategyInterface;
class UUIDFromObjectStrategy implements StrategyInterface
{
private $getter;
public function __construct($getter = 'getId')
{
$this->getter = $getter;
}
/**
* Converts the given value so that it can be extracted by the hydrator.
*
* @param mixed $value The original value.
* @return mixed Returns the value that should be extracted.
*/
public function extract($value)
{
if(is_object($value) && method_exists($value, $this->getter)) {
if($value->{$this->getter}() instanceof Uuid) {
return (string) $value->{$this->getter}();
}
}
return $value;
}
/**
* Converts the given value so that it can be hydrated by the hydrator.
*
* @param mixed $value The original value.
* @return mixed Returns the value that should be hydrated.
*/
public function hydrate($value)
{
return Uuid::fromString($value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment