You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.8 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 Jairo Llopis <jairo.llopis@tecnativa.com>
  3. # Copyright 2017 Pedro M. Baeza <pedro.baeza@tecnativa.com>
  4. # License LGPL-3 - See http://www.gnu.org/licenses/lgpl-3.0.html
  5. from odoo import _, api, fields, models
  6. from odoo.exceptions import ValidationError
  7. class CustomInfoTemplate(models.Model):
  8. """Defines custom properties expected for a given database object."""
  9. _description = "Custom information template"
  10. _name = "custom.info.template"
  11. _order = "model_id, name"
  12. _sql_constraints = [
  13. ("name_model",
  14. "UNIQUE (name, model_id)",
  15. "Another template with that name exists for that model."),
  16. ]
  17. name = fields.Char(required=True, translate=True)
  18. model = fields.Char(
  19. string="Model technical name", inverse="_inverse_model",
  20. compute="_compute_model", search="_search_model"
  21. )
  22. model_id = fields.Many2one(
  23. comodel_name='ir.model', string='Model', ondelete="restrict",
  24. required=True, auto_join=True,
  25. )
  26. property_ids = fields.One2many(
  27. comodel_name='custom.info.property', inverse_name='template_id',
  28. string='Properties', oldname="info_ids",
  29. )
  30. @api.multi
  31. @api.depends("model_id")
  32. def _compute_model(self):
  33. for r in self:
  34. r.model = r.model_id.model
  35. @api.multi
  36. def _inverse_model(self):
  37. for r in self:
  38. r.model_id = self.env["ir.model"].search([("model", "=", r.model)])
  39. @api.model
  40. def _search_model(self, operator, value):
  41. models = self.env['ir.model'].search([('model', operator, value)])
  42. return [('model_id', 'in', models.ids)]
  43. @api.onchange('model')
  44. def _onchange_model(self):
  45. self._inverse_model()
  46. @api.multi
  47. def _check_model_update_allowed(self, model_id):
  48. """Check if the template's model can be updated.
  49. Template can be updated only if no property values already exists for
  50. this template
  51. """
  52. for record in self:
  53. if (model_id != record.model_id.id
  54. and record.mapped("property_ids.info_value_ids")):
  55. raise ValidationError(
  56. _("You cannot change the model because it is in use.")
  57. )
  58. @api.multi
  59. def check_access_rule(self, operation):
  60. """You access a template if you access its model."""
  61. for record in self:
  62. model = self.env[record.model_id.model or record.model]
  63. model.check_access_rights(operation)
  64. model.check_access_rule(operation)
  65. return super(CustomInfoTemplate, self).check_access_rule(operation)
  66. @api.multi
  67. def write(self, vals):
  68. if 'model_id' in vals:
  69. self._check_model_update_allowed(vals['model_id'])
  70. return super(CustomInfoTemplate, self).write(vals)