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.

81 lines
2.7 KiB

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