So, i'm building a small form with a choice. However, i want to pre-select some of those options, as if i was applying selected="selected". Could not find how in the docs. Help? :D
Ended up being simpler than i thought:
$form['form[selectionMenu]']->select(1);
To set default values for a form those values need to be set in the underlying data class for the form. Assuming the underlying data class is an Entity, the values can be defaulted in that Entity on construction. If you are not using entity annotations and don't want to alter your generated entity classes you can set default values into a new instance of the entity class and use it as the data for your form.
For example, for a User entity which has an array of roles and a method setRoles(array $roles) the roles can be defaulted in the constructor of the User entity like this (hardcoded strings used for clarity):
public function __construct()
{
$this->setRoles(array('ROLE_USER', 'ROLE_READER', 'ROLE_EDITOR');
}
Alternatively, the roles can be defaulted in the controller just before the form is displayed like this (simplistic example with no form class and hardcoded strings):
$allRoles = array('ROLE_USER', 'ROLE_READER', 'ROLE_EDITOR', 'ROLE_ADMIN', 'ROLE_SUPER_ADMIN');
$user = new User();
$user->setRoles(array('ROLE_USER', 'ROLE_READER', 'ROLE_EDITOR');
$form = $this->createFormBuilder($user)
->add('username', 'text')
->add('roles', 'choice', array('choices' => array_combine($allRoles, $allRoles),
'multiple' => true)
->getForm();
return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));