0

I made all the other entries false if one entry is true. How do I protect this entry from being deleted? There must always be at least one entry.

res.partner.xml

<odoo>


    <record id="view_partner_form_inherit" model="ir.ui.view">
        <field name="name">res.partner.form</field>
        <field name="model">res.partner</field>
        <field name="inherit_id" ref="base.view_partner_form"/>
        <field name="arch" type="xml">

            <xpath expr="//form/sheet/group/group/field[@name='mobile']" position="after">
                <field name="is_primary" string='Is primary'/>
            </xpath>

            <div t-att-class="color + (record.title.raw_value == 1 ? ' oe_kanban_color_alert' : '') + ' oe_kanban_global_click'">
            <div style="float: right; margin-top:-25%;">
                <xpath expr="//div[hasclass('oe_kanban_details')]" position="inside">
                    <field name="is_primary" widget="checkbox"/>
                </xpath>
            </div>
        </div>
        </field>

    </record>


</odoo>

Primary_contact.py

from odoo import api, fields, models, _

class PartnerPrimary(models.Model):
    _inherit = "res.partner"
    is_primary = fields.Boolean(string='Is primary')

@api.constrains('is_primary')
def check_is_primary(self):
    if self.is_primary:
        contacts_ids = self.parent_id.child_ids.filtered(lambda lm: lm.id != self.id)
        for cont in contacts_ids:
            cont.is_primary = False
  • Not sure about the extent of the requirement.. Why not create a mandatory many2one field for primary_contact with filtered childs_ids of this partner. It will satisfy all your current conditions ? You can select only one/you cannot delete(mandatory) – NinjaBat May 16 '22 at 09:41
  • @NinjaBat Wow, thanks) That's an interesting solution. I need to think about the implementation –  May 16 '22 at 09:57
  • @NinjaBat can you help me with this? –  May 16 '22 at 10:27

1 Answers1

0

I solved this problem

class PartnerPrimary(models.Model):
    _inherit = "res.partner"
    is_primary = fields.Boolean(string='Is primary')

    @api.constrains('is_primary')
    def check_is_primary(self):
        if self.is_primary:
            contacts_ids = self.parent_id.child_ids.filtered(lambda lm: lm.id != self.id)
            for cont in contacts_ids:
                cont.is_primary = False


    def unlink(self):
        for delete in self:
            if delete.is_primary:
                raise UserError(('You cannot delete'))
            return super(PartnerPrimary, self).unlink()