How to set up default value in symfony2 select box with data from database

Deadly 提交于 2019-11-28 02:18:41

问题


I have this code

->add('user', 'entity', array(
                            'class' => 'Acme\Entity\User',
                            'query_builder' => function(EntityRepository $er) use ($options)
     {                        return $er->createQueryBuilder('u')
                               ->orderBy('u.name', 'ASC');
                            },
            'data' => $option['id']
            ))

Its not working

public function buildForm(FormBuilderInterface $builder, array $options)


    {
            $builder
              ->add('description')

              ->add('user', 'entity', array(
                'class' => 'Acme\Entity\User',
                'query_builder' => function(EntityRepository $er) use ($options) {
                    return $er->createQueryBuilder('u');

                },
              'preferred_choices' => array('2')
              ))
        ;
    }

回答1:


You can use the one of the following:

  1. Set a default value in the object

    $cl->setUser($this->getDoctrine()->getEntityManager()->getReference('Acme:User',2));
    
  2. Use a preferred choices option in the form builder:

    'preferred_choices' => array('2')
    
  3. Or set 'property_path' => false and use a 'data' => YourDefaultEnity




回答2:


The form should map the user->id value automatically to the selected entity select field. For example if your have a Computer entity that has a OnetoOne relationship with a User entity in a join table called 'computer_users':

class Computer{

    private $user;

    /**
    * @ORM\OneToOne(targetEntity="ComputerUser", mappedBy="computer")
    */
    private $computerUsers;

    public function getUser(){
       return $computerUsers->getUser();
    }

    private function getComputerUser(){
       return $this->$computerUsers;
    }
}

The field 'user' in the form class should pick up the user->id value from the 'user' attribute object in the Computer class passed to the form.

Alternatively, you can explicitly set the value by explicitly passing the user entity into the form using SetData():

    $computerForm = $this->createForm( new ComputerForm(), $computer );
    $user         = $computer->getComputerUser()->getUser();

    $computerForm->get('user')->setData( $user );

    return $this->render( 'AcmeBundle:Computer:edit.html.twig'
                        , array( 'computer' => $computer
                        , 'computerForm'    => $computerForm->createView()
            )
    );


来源:https://stackoverflow.com/questions/11999745/how-to-set-up-default-value-in-symfony2-select-box-with-data-from-database

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