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

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']
            ))

Does not work

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
source share
2 answers

You can use one of the following actions:

  • Set the default value in the object

    $cl->setUser($this->getDoctrine()->getEntityManager()->getReference('Acme:User',2));
    
  • Use your preferred choice in the form builder:

    'preferred_choices' => array('2')
    
  • Or install 'property_path' => falseand use'data' => YourDefaultEnity

+5
source

The form should automatically display the value user-> id in the selected object selection field. For example, if you have a Computer object that has an OnetoOne relationship with a User object in the connection 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;
    }
}

"" user- > id "" "", .

, 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()
            )
    );
0

Source: https://habr.com/ru/post/1544908/


All Articles