put data form database into checkbox symfony 3

痴心易碎 提交于 2019-12-25 08:59:11

问题


I started learn symfony 3. For the first project i chose a simple totodlist.

So now i have possibility to create and save the user in my database. Next I can create a task for them.

I want to create a checkbox where can i choose a users to perform a task.

So i need put data from my user database to checkbox form ($temp_users varbiable). I don't know how to do it.

Can anybody show me how to do it.

below is my code:

public function createAction(Request $request)
{

    $todo = new Todo;

    $users = $this->getDoctrine()
    ->getRepository('AppBundle:User')
    ->findAll();

    $temp_users = array();
    foreach($users as $user) {
    $temp_users[$user->getUsername()] = $user->getId();

}

 $form = $this->createFormBuilder($todo)
     ->add('name', TextType::class, array('attr' => array('class' => 'form-     control', 'style' => 'margin-bottom:15px')))


    ->add('wykona', CheckboxType::class, array('label' => $temp_users, 'required' => false,))

回答1:


I'm not sure what you mean by checkbox - are you wanting to select one, or many users? I'm going to assume you want to select just one for simplicity's sake (you can adapt this to your liking)

You don't need to get all the users like you're trying to do, something like this should work (untested)

$form = $this->createFormBuilder($todo)
    ->add('user', EntityType::class, array(
        'label' => 'Name',
        'class' => AppBundle\Entity\User::class,
        'choice_label' => 'name', //if you have a variable 'name' in your User entity, otherwise you will need a __toString method in the User entity
    ));



回答2:


Try this code inside your createAction.

ADD this into your code

$form = $this->createFormBuilder($todo)
       ->add('users', EntityType::class, array(
                'class' => 'AppBundle:User',
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                                 ->orderBy('u.name', 'ASC')
                         },
                'choice_label' => 'name',
                'multiple' => true,
                'expanded' => true,
            ));

Also you don't need the following code anymore inside createAction.

REMOVE Below code from your code

$users = $this->getDoctrine()
        ->getRepository('AppBundle:User')
        ->findAll();

$temp_users = array();
foreach($users as $user) {
$temp_users[$user->getUsername()] = $user->getId();


来源:https://stackoverflow.com/questions/40627526/put-data-form-database-into-checkbox-symfony-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!