Skip to content

Instantly share code, notes, and snippets.

@rosstuck
Last active January 5, 2017 11:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rosstuck/10353816 to your computer and use it in GitHub Desktop.
Save rosstuck/10353816 to your computer and use it in GitHub Desktop.
Symfony Formset
<?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());
<?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