Search code examples
formssymfony1doctrineforeign-keys

How to set a foreign key to null ? (symfony)


I have a form with an input which is optionnal but I can't valid the form if the user don't fill it because it's a foreign key and Doctrine shows me an error.

SQLSTATE[HY000]: General error: 1452 Cannot add or update a child row: a foreign key constraint fails (`logements`.`bail`, CONSTRAINT `bail_ibfk_3` FOREIGN KEY (`locataire2`) REFERENCES `locataire` (`nud`) ON DELETE CASCADE ON UPDATE CASCADE)

I have tried in phpMyAdmin the same request and it works correctly : I can set the foreign key to null.

So, how can I set the foreign key to null and valid the form without Doctrine error ?

EDIT

Bail:
  connection: doctrine
  tableName: bail
  columns:
    id:
      type: integer(2)
      fixed: false
      unsigned: true
      primary: true
      autoincrement: true
    locataire1:
      type: string(20)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    locataire2:
      type: string(20)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    logement:
      type: integer(2)
      fixed: false
      unsigned: true
      primary: false
      notnull: false
      autoincrement: false
    datedeb:
      type: date(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    datefin:
      type: date(25)
      fixed: false
      unsigned: false
      primary: false
      default: '0000-00-00'
      notnull: false
      autoincrement: false
    colloc:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: false
      default: '0'
      notnull: false
      autoincrement: false
    bailglissant:
      type: string(12)
      fixed: false
      unsigned: false
      primary: false
      default: 'Non spécifié'
      notnull: false
      autoincrement: false
  relations:
    Locataire:
      local: locataire1
      foreign: nud
      type: one
    Logement:
      local: logement
      foreign: id
      type: one
    Locataire_3:
      class: Locataire
      local: locataire2
      foreign: nud
      type: one

Solution

  • I have resolved the problem by using the method processValues() (call by save()) to set attributes to NULL.