Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y taberna
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Brewery
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y asistencia informática
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

I want to modify the partner form in odoo 18 enterprise; How to edit code?

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
development
1 Responder
2497 Vistas
Avatar
شركة مهارات للتقنية وتنمية الموارد البشرية

I would like help with the following: - I want to modify the partner form by adding three fields: nationality, gender, and ID. This way, I can search for a customer within the partner form from any application using the search bar by entering their mobile number, ID number, or name (which is the default in Odoo) and simply pressing Enter.  - I want to set the conditions for the mobile number to be 0553449910, because when adding the number, the country code is added, and when searching, I was unable to do so. As for the ID, if the nationality is Saudi, the ID number must begin with 1, otherwise it must begin with 2.

I don't select but press enter


To be the same search by name

from odoo import models, fields, api, _

from odoo.exceptions import ValidationError

import re


class ResPartner(models.Model):

_inherit = 'res.partner'


identity_number = fields.Char(string="Identity Number", index=True, size=10) # Added size limit

gender = fields.Selection([('male', 'Male'), ('female', 'Female')], string="Gender")

nationality_id = fields.Many2one('res.country', string='nationality')


_sql_constraints = [

('unique_identity_number', 'unique(identity_number)', 'ID number already used.'),

('unique_phone_number', 'unique(phone)', 'Phone number already used.') # Renamed constraint for clarity

]


@api.constrains('identity_number', 'nationality_id')

def _check_identity_number_format(self):

for rec in self:

number = (rec.identity_number or '').strip()

if number:

if not number.isdigit():

raise ValidationError(_("ID number must contain number."))

if len(number) != 10:

raise ValidationError(_("The ID number must consist of only 10 digits."))



if rec.nationality_id:

if rec.nationality_id.code == 'SA' and not number.startswith('1'):

raise ValidationError(_("The ID number for Saudis must start with the number 1."))

elif rec.nationality_id.code != 'SA' and not number.startswith('2'):

raise ValidationError(_("The ID number for non-Saudis must start with the number 2."))


@api.constrains('phone')

def _check_phone_format(self):

for rec in self:

phone = (rec.phone or '').strip()

if phone:

clean_phone = re.sub(r'\D', '', phone)

if not clean_phone.isdigit():

raise ValidationError(_("Phone number contain numbers only."))

if len(clean_phone) != 10:

raise ValidationError(_("Phone number must be 10 digits."))


@api.model

def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):

args = args or []

domain = []


if name:

# Clean the name input to only contain digits for numerical searches

clean_name = re.sub(r'\D', '', name)

# Base search domain for name, phone, and identity_number

search_domain = ['|', '|',

('name', operator, name),

('phone', operator, name),

('identity_number', operator, name)]

# If the cleaned name is numeric, add specific phone/identity number search conditions

if clean_name:

# If it looks like a full 10-digit number (potential phone or identity)

if len(clean_name) == 10:

search_domain.extend(['|',

('phone', '=', clean_name),

('identity_number', '=', clean_name)])

# Handle partial matches for phone and identity number as well if needed

elif len(clean_name) <= 10: # For partial numerical searches

search_domain.extend(['|',

('phone', operator, clean_name),

('identity_number', operator, clean_name)])


domain = search_domain + args

else:

domain = args


return self.search(domain, limit=limit).name_get()



#XML 

<odoo>

<record id="view_partner_form_inherit_training" model="ir.ui.view">

<field name="name">res.partner.form.training.center</field>

<field name="model">res.partner</field>

<field name="inherit_id" ref="base.view_partner_form"/>

<field name="arch" type="xml">


<xpath expr="//field[@name='website']" position="before">

<field name="identity_number" placeholder="Ex: 1012345678" required="1"/>

<field name="gender"/>

<field name="nationality_id"/>

</xpath>


<xpath expr="//field[@name='mobile']" position="replace">

</xpath>


<xpath expr="//field[@name='phone']" position="attributes">

<attribute name="placeholder">05XXXXXXXX</attribute>

<attribute name="required">1</attribute>

</xpath>


</field>

</record>

</odoo>

0
Avatar
Descartar
شركة مهارات للتقنية وتنمية الموارد البشرية
Autor

How do I prevent the user from entering more than 10 numbers only?

<xpath expr="//field[@name='phone']" position="attributes">
<attribute name="placeholder">05XXXXXXXX</attribute>
<attribute name="required">1</attribute>
<attribute name="maxlength">10</attribute>

شركة مهارات للتقنية وتنمية الموارد البشرية
Autor

How do I prevent the user from entering more than 10 numbers only?

<xpath expr="//field[@name='phone']" position="attributes">

    <attribute name="placeholder">05XXXXXXXX</attribute>

    <attribute name="required">1</attribute>

    <attribute name="options">{'maxlength': '10'}</attribute>

</xpath>


شركة مهارات للتقنية وتنمية الموارد البشرية
Autor

Thanks
I'm entered 0553448953

Avatar
D Enterprise
Mejor respuesta

Hii,

Here is updated code please check 

from odoo import models, fields, api, _ from odoo.exceptions import ValidationError import re class ResPartner(models.Model): _inherit = 'res.partner' identity_number = fields.Char(string="Identity Number", index=True, size=10) gender = fields.Selection([('male', 'Male'), ('female', 'Female')], string="Gender") nationality_id = fields.Many2one('res.country', string='Nationality') _sql_constraints = [ ('unique_identity_number', 'unique(identity_number)', 'ID number already used.'), ('unique_phone_number', 'unique(phone)', 'Phone number already used.') ] @api.constrains('identity_number', 'nationality_id') def _check_identity_number_format(self): for rec in self: number = (rec.identity_number or '').strip() if number: if not number.isdigit(): raise ValidationError(_("ID number must contain only digits.")) if len(number) != 10: raise ValidationError(_("The ID number must be exactly 10 digits.")) if rec.nationality_id: if rec.nationality_id.code == 'SA' and not number.startswith('1'): raise ValidationError(_("The ID number for Saudis must start with 1.")) elif rec.nationality_id.code != 'SA' and not number.startswith('2'): raise ValidationError(_("The ID number for non-Saudis must start with 2.")) @api.constrains('phone') def _check_phone_format(self): for rec in self: phone = (rec.phone or '').strip() if phone: clean_phone = re.sub(r'\D', '', phone) if not clean_phone.isdigit(): raise ValidationError(_("Phone number must contain digits only.")) if len(clean_phone) != 10: raise ValidationError(_("Phone number must be exactly 10 digits (e.g., 05XXXXXXXX).")) @api.model def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None): args = args or [] domain = [] if name: clean_name = re.sub(r'\D', '', name) search_domain = ['|', '|', ('name', operator, name), ('identity_number', operator, clean_name), ('phone', operator, name), ] # Convert +966xxxxxxxxx to 05xxxxxxxx if clean_name: local_number = clean_name if clean_name.startswith('966') and len(clean_name) == 12: local_number = '0' + clean_name[3:] # 966553449910 → 0553449910 if len(local_number) == 10: search_domain += ['|', ('phone', 'ilike', local_number), ('mobile', 'ilike', local_number) ] domain = search_domain + args else: domain = args return self.search(domain, limit=limit).name_get()

XML View File 

<odoo> <record id="view_partner_form_inherit_identity" model="ir.ui.view"> <field name="name">res.partner.form.identity.fields</field> <field name="model">res.partner</field> <field name="inherit_id" ref="base.view_partner_form"/> <field name="arch" type="xml"> <!-- Insert fields before website field --> <xpath expr="//field[@name='website']" position="before"> <field name="identity_number" placeholder="Ex: 1012345678" required="1"/> <field name="gender"/> <field name="nationality_id"/> </xpath> <!-- Replace mobile field to show it again --> <xpath expr="//field[@name='mobile']" position="replace"> <field name="mobile" placeholder="05XXXXXXXX"/> </xpath> <!-- Add attributes to phone --> <xpath expr="//field[@name='phone']" position="attributes"> <attribute name="placeholder">05XXXXXXXX</attribute> <attribute name="required">1</attribute> </xpath> </field> </record> </odoo>

i hope it is usefull

1
Avatar
Descartar
شركة مهارات للتقنية وتنمية الموارد البشرية
Autor

Thank you

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Feature Request: Native “Dialog Filters” in Search Panel
development
Avatar
0
nov 25
138
Solution to the Getting Started tutorial from the official Odoo 16 documentation
development
Avatar
Avatar
Avatar
2
nov 25
1510
How do I change the name of the module, or rather the name assigned to the module, after I created it in Odoo Studio?
development
Avatar
1
nov 25
364
Guest House Module - Rental Search Bar
development
Avatar
Avatar
1
nov 25
234
How to make all branches for user active automatically after login his account?
development
Avatar
Avatar
Avatar
3
nov 25
429
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now