Last active
March 27, 2016 22:26
-
-
Save tystr/2491950 to your computer and use it in GitHub Desktop.
Doctrine Symfony2 Form Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Form\Handler; | |
use Symfony\Component\Form\Form; | |
use Symfony\Component\HttpFoundation\Request; | |
use Doctrine\Common\Persistence\ObjectManager; | |
use Form\Handler\FormHandlerInterface; | |
/** | |
* Doctrine form handler for persisting doctrine objects | |
* | |
* Provides basic functionality of binding a request to a form, setting flash messages, | |
* and persisting the form's underlying object. This class should be extended to override the | |
* default functionality. | |
* | |
* @author Tyler Stroud <[email protected]> | |
*/ | |
class DoctrineFormHandler implements FormHandlerInterface | |
{ | |
/** | |
* @var Form | |
*/ | |
protected $form; | |
/** | |
* @var Request | |
*/ | |
protected $request; | |
/** | |
* @var ObjectManager | |
*/ | |
protected $om; | |
/** | |
* @var string | |
*/ | |
protected $requestMethod = 'POST'; | |
/** | |
* @param Request $request The request object | |
* @param ObjectManager $om The object manager | |
* @param Form $form The form object | |
*/ | |
public function __construct(Request $request, ObjectManager $om, Form $form) | |
{ | |
$this->form = $form; | |
$this->request = $request; | |
$this->om = $om; | |
} | |
/** | |
* Set requestMethod | |
* | |
* @param string $method A valid HTTP method (for example, GET or POST) | |
*/ | |
public function setRequestMethod($method) | |
{ | |
$this->requestMethod = $method; | |
} | |
/** | |
* Process the form | |
* | |
* @param mixed $object An object mapped by Doctrine | |
* | |
* @throws \RuntimeException | |
* @throws \InvalidArgumentException | |
* @return bool | |
*/ | |
public function process($object) | |
{ | |
if (false === is_object($object)) { | |
throw new \InvalidArgumentException(sprintf('The process method\'s argument must be an object, "%s" given.', gettype($object))); | |
} | |
$this->form->setData($object); | |
if ($this->requestMethod === $this->request->getMethod()) { | |
$this->form->bindRequest($this->request); | |
if ($this->form->isValid()) { | |
$this->onSuccess($object); | |
return true; | |
} | |
return false; | |
} | |
} | |
/** | |
* Called if the form validates successfully | |
* | |
* @param mixed $object | |
*/ | |
protected function onSuccess($object) | |
{ | |
$this->om->persist($object); | |
$this->om->flush(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment