Automatically build a form using entity (one to one relationship)

13,463

Try to use Collection form type instead of Entity field type – see this tutorial.

Share:
13,463
Manu
Author by

Manu

What?

Updated on July 20, 2022

Comments

  • Manu
    Manu almost 2 years

    I'm wondering if it is possible to build a form using an entity to get all the fields, in a one-to-one relationship. To clarify:

    I have an User.php entity (with all the obvious fields, name, surname, genre, etc) and a Address.php entity. What I want is to build the whole form without adding one by one the properties of Address entity and save it with the proper relationship in the database.

    This is what I've tried (i've trimed the code a little bit), but obviously is not the correct way:

    User entity:

    class User implements UserInterface {
    
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    
    
    /**
     * @ORM\Column(type="string", length=100, nullable=TRUE)
     */
    protected $firstName;
    
    /**
     * @ORM\Column(type="string", length=200)
     * @Assert\NotBlank()
     */
    protected $lastNames;
    
    /**
     * @ORM\OneToOne(targetEntity="Capsa\Bundle\ClubCommonBundle\Entity\Address")
     */
    protected $address;
    

    Address class

    class Address {
    
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    
    /**
     * @ORM\Column(type="string", length=100, unique=TRUE)
     * @Assert\NotBlank()
     */
    protected $streetName;
    
    /**
     * @ORM\Column(type="string", length=50)
     */
    protected $streetNumber;
    

    Form builder:

    public function buildForm(FormBuilder $builder, array $options) {
        $builder->add('login', 'text')
                ->add('password', 'password')
                ->add('firstName', 'text', array("required" => FALSE))
                ->add('lastNames', 'text')
                ->add('address', 'entity', array(
                    'class' => 'CapsaClubCommonBundle:Address',
                    'property'=>'streetName'
                ));
    }
    

    That only gets the field streetName of the table and puts it in a list.

  • Manu
    Manu over 12 years
    finally I used just this to load the whole object: ->add('address', new AddressType()); of course, defyining AddressType
  • Paolo Stefan
    Paolo Stefan over 8 years
    @Manu your comment is really the answer - al least the one that worked for me. Thanks.
  • 0x1gene
    0x1gene over 7 years
    Following Manu's comment here is the newer syntax : ->add('address', AddressType::class)