You do not have to pass users to your view. Just create a UsersType with multiple choices enabled and do what you want to do on submit. The following code has not been tested.
class UsersType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('users', 'entity', array(
'required' => false,
'class' => 'MeMyBundle:UserEntity',
'property' => 'id',
'property_path' => '[id]', # in square brackets!
'multiple' => true,
'expanded' => true
));
}
}
Create your controller action
/**
* @Route("/my_users", name="_users")
* @Template()
*/
public function usersAction()
{
$request = $this->get('request');
$users = $this->get('my_user_manager')->findAll() //get all users. Fit this line depending on your app.
$form = $this->createForm(new UsersType(), $users); // I assume you have a UsersType here.
$form->bind($request);
if ($form->isValid()) {
$data = $form->getData();
foreach ($data['users'] as $user) {
// Do what you want with $user, it contains one selected user
}
//you can redirect here
}
return array(
'users' => $users,
'form' => $form->createView(),
);
}
Now in your view, you can select your users :
{% block body %}
{% if is_granted('ROLE_ADMIN') %}
{{ form_start(form) }}
{{ form_errors(form) }}
...
<input type="submit" />
{{ form_end(form) }}
{% else %}
{# Render a list #}
<ul>
{% for user in users %}
<li>{{user.username}}</li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}