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

后端 未结 2 1914
清歌不尽
清歌不尽 2020-12-18 16:32

I have this code

->add(\'user\', \'entity\', array(
                            \'class\' => \'Acme\\Entity\\User\',
                            \'quer         


        
2条回答
  •  情歌与酒
    2020-12-18 17:04

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

提交回复
热议问题