Skip to content

Instantly share code, notes, and snippets.

@rosstuck
Last active January 5, 2017 11:28

Revisions

  1. rosstuck revised this gist Apr 10, 2014. 1 changed file with 11 additions and 0 deletions.
    11 changes: 11 additions & 0 deletions FormSet.php
    Original file line number Diff line number Diff line change
    @@ -12,6 +12,7 @@ class FormSet

    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();
    }

    @@ -40,4 +41,14 @@ protected function getActiveForm(Request $request)
    }
    }
    }

    public function createViews()
    {
    $views = [];
    foreach ($this->forms as $form) {
    $views[] = $form->createView();
    }

    return $views;
    }
    }
  2. rosstuck revised this gist Apr 10, 2014. 2 changed files with 0 additions and 0 deletions.
    File renamed without changes.
    File renamed without changes.
  3. rosstuck created this gist Apr 10, 2014.
    43 changes: 43 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    <?php
    use \Symfony\Component\Form\FormInterface;
    use \Symfony\Component\HttpFoundation\Request;


    class FormSet
    {
    /**
    * @var SplObjectStorage|FormInterface[]
    */
    protected $forms;

    public function __construct()
    {
    $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;
    }
    }
    }
    }
    15 changes: 15 additions & 0 deletions gistfile2.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,15 @@
    <?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());