简体   繁体   中英

1 to 1..0 relationship in an embedded form with doctrine and symfony2

One user may have just 1 item or none. (1-1..0 relationship)

I'm trying to accomplish that in symfony2 with doctrine.

I've accomplished an 1 to 1 relationship, it's fairly simple. But how can I specify to doctrine that when I want to create an user, the item can be null? (and not to insert a new row and just leave id_item null)

This is what I have:

user.orm.yml file

oneToOne:
  userItem:
    targetEntity: SOA\AXBundle\Entity\Items
    cascade: ["remove", "persist"]
    joinColumn:
      name: id_item        
      referencedColumnName: id        
      nullable: true

And of course, I created ItemsTypeForm class, and added the type in my userstypeform class:

    // UsersTypeForm Class
    ->add('userItem', new \SOA\AXBundle\Form\ItemsTypeForm())

Controller Action is like this,

public function addUserAction(Request $request) {

  $user = new User();

  $form = $this->createForm(new UseType(), $user);

  if ($request->getMethod() == 'POST') {

     $form->bindRequest($request);

     if ($form->isValid()) {

         $em = $this->getDoctrine()->getEntityManager();
         $em->persist($user);
         $em->flush();

         return $this->redirect($this->generateUrl('homepage'));
     }
  }

}

When I add a new user, everything goes fine. The user is inserted as well as the item. But when I try to add an user where it has no item (user item fields are blank), I get the following error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null

It is trying to insert the item, with null values.

While I can live with an 1 to 1 relationship, I would like to learn how to make an 1 to 1..0 relationship.

Database schema is all right (you can check that if you look directly into your db at User table definition, I'm pretty sure that you can use null for "item_id" field).

The problem is when you fill your form and submit it, Symfony creates Item object with every fields set as null (because every field in your form related to item are empty). You must tell somehow that if every field is null then framework shouldn't persist Item object. In my opinion to achieve this the best way is use DataTransformer.

You can read about it here:

http://symfony.com/doc/2.0/cookbook/form/data_transformers.html

Generally in transformer::reverseTransform you check if every fields is empty, and if yes then you return null instead of Item object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM