Last active
January 5, 2017 11:28
-
-
Save rosstuck/10353816 to your computer and use it in GitHub Desktop.
Symfony Formset
This file contains hidden or 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 | |
$formset = new FormSet(); | |
$formset->addForm( | |
$this->createForm('form_1', $foo), | |
function($form) use ($commandBus) { | |
$commandBus->execute($form->getData()); | |
} | |
); | |
$formset->addForm( | |
$this->createForm('form_1', $bar), | |
function() { | |
echo 'form 2 complete, yay!'; | |
} | |
); | |
$formset->submitRequest(new Request()); |
This file contains hidden or 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 | |
use \Symfony\Component\Form\FormInterface; | |
use \Symfony\Component\HttpFoundation\Request; | |
class FormSet | |
{ | |
/** | |
* @var SplObjectStorage|FormInterface[] | |
*/ | |
protected $forms; | |
public function __construct() | |
{ | |
// TODO: Maybe a[$form->getName() is better] What if two forms with the same name, would fail isSubmitted check... | |
$this->forms = new SplObjectStorage(); | |
} | |
public function addForm(FormInterface $form, callable $onComplete) | |
{ | |
$this->forms[$form] = ['form' => $form, 'onComplete' => $onComplete]; | |
} | |
public function submitRequest(Request $request) | |
{ | |
$form = $this->getActiveForm($request); | |
if (!$form || !$form->isValid()) { | |
return; | |
} | |
// Invoke completed callback | |
$this->forms[$form]['onComplete']($form); | |
} | |
protected function getActiveForm(Request $request) | |
{ | |
foreach ($this->forms as $form) { | |
$form->handleRequest($request); | |
if ($form->isSubmitted()) { | |
return $form; | |
} | |
} | |
} | |
public function createViews() | |
{ | |
$views = []; | |
foreach ($this->forms as $form) { | |
$views[] = $form->createView(); | |
} | |
return $views; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment