Reputation: 65
I have 2 questions. First one.
This field have to be integer greater or equal than to 50. how can i do this.
value = fields.Integer("Value", required=True)
second question.
i wanted to add search by "name" but if i run this coed i getting TypeError:Type is not constructor. what is wrong with my search section? without search section it runs normal.
<record model="ir.ui.view" id="helloworld.list2">
<field name="name">helloworld listx</field>
<field name="model">helloworld.test2</field>
<field name="arch" type="xml">
<search>
<field name="name"/>
</search>
<tree>
<field name="name"/>
<field name="reference"/>
</tree>
</field>
</record>
UPDATE.
from openerp import models, fields, api
from openerp.exceptions import ValidationError
class HelloWorld(models.Model):
_name = 'helloworld.test'
name = fields.Char("Name", required=True, size=20)
value = fields.Integer("Value", required=True)
# I am adjusting the indentation below so the methods become part of your class
@api.onchange('value')
def _onchange_value(self):
for record in self:
if record.value < 20:
raise ValidationError("Your record is too small: %s" % record.value)
Upvotes: 0
Views: 454
Reputation: 3378
There are a couple of ways it could be done however the 'constrains' decorator is probably what you want. If not you could override the 'write' and 'create' methods to raise exceptions.
The constrains functions will run before a write or creation of a record. And will not allow the record to be written unless the value passes the validation.
from odoo.exceptions import ValidationError
@api.constrains('value')
def _check_value_field(self):
for record in self:
if record.value < 50:
raise ValidationError("Your record is too small: %s" % record.value)
With regards to your search view. You also have a tree view. The search view and tree view are separate things altogether. You should define them separately.
<record model="ir.ui.view" id="helloworld.tree2">
<field name="name">test2.tree</field>
<field name="model">helloworld.test2</field>
<field name="arch" type="xml">
<tree>
<field name="name"/>
<field name="reference"/>
</tree>
</field>
</record>
<record model="ir.ui.view" id="helloworld.search2">
<field name="name">test2.search</field>
<field name="model">helloworld.test2</field>
<field name="arch" type="xml">
<search>
<field name="name"/>
</search>
</field>
</record>
You can if you wish provide immediate validation of field data using an 'onchange' function as well (as CZoellner recommended), this will immediately notify the user the entered value is invalid however should not be used for record validation as the user can simply bypass the error message. Here is an example.
from odoo.exceptions import ValidationError
@api.onchange('value')
def _onchange_value(self):
for record in self:
if record.value < 50:
raise ValidationError("Your record is too small: %s" % record.value)
Upvotes: 2