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.
Here are some examples of one-to-one relationships in the home: One family lives in one house, and the house contains one family. One person has one passport, and the passport can only be used by one person. One person has one ID number, and the ID number is unique to one person.
To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship. I mean to say, define the foreign key table. Thanks for reading this article, hope you enjoyed it.
You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B.
Try to use Collection form type instead of Entity field type – see this tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With