Skip to content

Instantly share code, notes, and snippets.

/-

Created August 17, 2015 12:42
Show Gist options
  • Save anonymous/8d8dd618a7185c24d203 to your computer and use it in GitHub Desktop.
Save anonymous/8d8dd618a7185c24d203 to your computer and use it in GitHub Desktop.
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\FormEvents;
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$opt1 = new Opt(1);
$opt2 = new Opt(2);
$opt3 = new Opt(3);
$form = $this->createFormBuilder()
->addEventListener(FormEvents::PRE_SUBMIT, function($event) use($opt1, $opt2, $opt3) {
$event->getForm()
->add('sub', 'choice', [
'multiple' => true,
'expanded' => true,
'choices_as_values' => true,
'choice_label' => 'label',
'choice_value' => 'id',
'choices' => [$opt1, $opt2, $opt3],
'data' => [$opt1, $opt3],
])
;
})
->add('submit', 'submit')
->getForm()
;
$form->handleRequest($request);
return $this->render('default/index.html.twig', array(
'form' => $form->createView(),
));
}
}
class Opt {
public $id;
public $label;
public function __construct($id)
{
$this->id = $id;
$this->label = "label for $id";
}
}
@docteurklein
Copy link

@webmozart when a choice is is added via a (PRE_SUBMIT) listener, data isn't taken into account, and checkboxes aren't pre-selected.

@webmozart
Copy link

Really? Interesting.. this should work IMO. Can you create a reproducible symfony-standard branch and open a ticket?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment