How to make field in OpenERP required only for specific workflow state?

Jordan Jambazov picture Jordan Jambazov · Jan 4, 2013 · Viewed 8.3k times · Source

In my OpenERP installation I have the following field, which wasn't required before, but I changed the required argument to True.

'fiscal_position': fields.many2one(
    'account.fiscal.position',
    'Fiscal Position',
    required=True,
    readonly=True,
    states={'draft':[('readonly',False)]}
    ),

In the debug log I see that the ORM tries to set a not null constraint for that field in the database.

2013-01-04 15:28:56 EET STATEMENT:  ALTER TABLE "account_invoice"
    ALTER COLUMN "fiscal_position" SET NOT NULL

How can I prevent that? My idea is to have the required True flag, only for new records and without having a NOT NULL constraint. In other cases PostgreSQL integrity errors occur:

IntegrityError: null value in column "fiscal_position" violates
    not-null constraint

So, how can I have a required field in the form view, without making the ORM touch the database scheme constraints? Or how can I change the field required dynamically, according to the state of the object?

Answer

Daniel Reis picture Daniel Reis · Jan 4, 2013

To make a field required only in some states, leave it as not required in the Model, and in the form view set the conditions on which the field will be required:

<field
    name="fiscal_position"
    attrs="{'required':[('state','in',['pending','open'])]}"
    />