Skip to Content
Odoo Menu
  • Sign in
  • Try it free
  • Apps
    Finance
    • Accounting
    • Invoicing
    • Expenses
    • Spreadsheet (BI)
    • Documents
    • Sign
    Sales
    • CRM
    • Sales
    • POS Shop
    • POS Restaurant
    • Subscriptions
    • Rental
    Websites
    • Website Builder
    • eCommerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Supply Chain
    • Inventory
    • Manufacturing
    • PLM
    • Purchase
    • Maintenance
    • Quality
    Human Resources
    • Employees
    • Recruitment
    • Time Off
    • Appraisals
    • Referrals
    • Fleet
    Marketing
    • Social Marketing
    • Email Marketing
    • SMS Marketing
    • Events
    • Marketing Automation
    • Surveys
    Services
    • Project
    • Timesheets
    • Field Service
    • Helpdesk
    • Planning
    • Appointments
    Productivity
    • Discuss
    • Approvals
    • IoT
    • VoIP
    • Knowledge
    • WhatsApp
    Third party apps Odoo Studio Odoo Cloud Platform
  • Industries
    Retail
    • Book Store
    • Clothing Store
    • Furniture Store
    • Grocery Store
    • Hardware Store
    • Toy Store
    Food & Hospitality
    • Bar and Pub
    • Restaurant
    • Fast Food
    • Guest House
    • Beverage Distributor
    • Hotel
    Real Estate
    • Real Estate Agency
    • Architecture Firm
    • Construction
    • Estate Management
    • Gardening
    • Property Owner Association
    Consulting
    • Accounting Firm
    • Odoo Partner
    • Marketing Agency
    • Law firm
    • Talent Acquisition
    • Audit & Certification
    Manufacturing
    • Textile
    • Metal
    • Furnitures
    • Food
    • Brewery
    • Corporate Gifts
    Health & Fitness
    • Sports Club
    • Eyewear Store
    • Fitness Center
    • Wellness Practitioners
    • Pharmacy
    • Hair Salon
    Trades
    • Handyman
    • IT Hardware & Support
    • Solar Energy Systems
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Others
    • Nonprofit Organization
    • Environmental Agency
    • Billboard Rental
    • Photography
    • Bike Leasing
    • Software Reseller
    Browse all Industries
  • Community
    Learn
    • Tutorials
    • Documentation
    • Certifications
    • Training
    • Blog
    • Podcast
    Empower Education
    • Education Program
    • Scale Up! Business Game
    • Visit Odoo
    Get the Software
    • Download
    • Compare Editions
    • Releases
    Collaborate
    • Github
    • Forum
    • Events
    • Translations
    • Become a Partner
    • Services for Partners
    • Register your Accounting Firm
    Get Services
    • Find a Partner
    • Find an Accountant
    • Meet an advisor
    • Implementation Services
    • Customer References
    • Support
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Get a demo
  • Pricing
  • Help

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

  • CRM
  • e-Commerce
  • Accounting
  • Inventory
  • PoS
  • Project
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Tags (View all)
odoo accounting v14 pos v15
About this forum
Help

A custom form widget causes weird undesirable side effects

Subscribe

Get notified when there's activity on this post

This question has been flagged
clientwidget
6640 Views
Avatar
Marvin Taboada

Hi, I have a fair simple example that uses a custom form widget, written previously using on_chage methods, that causes its form view to behave erratically. I'm using OpenERP 7.0, and object/view inheritance in a custom HR module.

Below are some brief details about the related requirement and the undesirable side effects that I would like to get rid of in my current implementation.

Requirement: The original HR module stores employee names in a single 'name' field ('name' is actually defined at 'resource.resource' and 'hr.employee' reuses it with delegation inheritance). We require to split the name into three fields, 'firstname' (required), 'middlename' (optional) and 'lastname' (required). At creation, an employee requires only 'firstname' and 'lastname', and 'name' should be hidden and should be automatically derived by concatenating the name-parts.

1st Solution - Server Side Based: Our first solution was to (1) hide the 'name' field in the form, (2) add the new three fields, and (3) define a single on_change method that concatenates the name-parts and fills the hidden 'name' field. This solution works well, but we want to move this logic completely to the client side to reduce the requests to the server, so it is currently discarded.

2nd Solution - Client Side Based: Based in the first first solution, (1) remove the on_change method and (2) use a custom form widget to listen changes in any of the name-parts, concatenate them and store the result in the 'name' field, directly in the client side. This solution partially works, name-parts are correctly concatenated at creating employees, but now the employee form does not correctly reset fields after employee edit/view, it renders dirty forms at attempting to create new employees (name-parts pre-populated with stale values) and renders inaccurate information at viewing records details in read mode. Only by navigating with the left/right arrows we are able to see accurate information. We used the following link as reference: https://doc.odoo.com/trunk/training/components/#the-form-view-custom-widgets

As I cannot attach the zipped module, below I'm adding the essential model/view/js sources of my module:

Model:

# -*- coding: utf-8 -*-

from openerp.osv import osv
from openerp.osv import fields

class hr_employee(osv.Model):
    """Customizations for 'hr.employee'."""
    _name = 'hr.employee'
    _inherit = 'hr.employee'

    def init(self, cursor):
        # New required fields: Update DB schema and data only when required
        cursor.execute('SELECT id FROM hr_employee '
                       'WHERE firstname IS NULL OR lastname IS NULL LIMIT 1')
        if cursor.fetchone():
            # Update required fields consistently
            cursor.execute('UPDATE hr_employee SET firstname = \'\' '
                           'WHERE firstname IS NULL')
            cursor.execute('UPDATE hr_employee SET lastname = name_related '
                           'WHERE lastname IS NULL')
            # Create SQL constraints, table is not empty
            cursor.execute('ALTER TABLE hr_employee '
                           'ALTER COLUMN firstname SET NOT NULL')
            cursor.execute('ALTER TABLE hr_employee '
                           'ALTER COLUMN lastname SET NOT NULL')

    _columns = {
        'firstname': fields.char("First Name", size=80, required=True),
        'middlename': fields.char("Middle Name", size=80),
        'lastname': fields.char("Last Name", size=80, required=True),
    }

hr_employee()

View:

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
        <record model="ir.ui.view" id="view_extended_employee_form">
            <field name="name">hr.employee.form.inherit</field>
            <field name="model">hr.employee</field>
            <field name="inherit_id" ref="hr.view_employee_form"/>
            <field name="priority" eval="20"/>
            <field name="arch" type="xml">
                <data>
                    <label for="name" class="oe_edit_only" position="replace"/>
                    <field name="name" position="replace">
                        <field name="name" invisible="True"/>
                    </field>
                    <label for="category_ids" position="before">
                        <label for="firstname"/>
                        <field name="firstname"/>
                        <label for="middlename"/>
                        <field name="middlename"/>
                        <label for="lastname"/>
                        <field name="lastname"/>
                        <widget type="concat_name_parts"/>
                    </label>
                </data>
            </field>
        </record>
    </data>
</openerp>

JavaScript (widgets):

openerp.hr_extra = function(openerp) {
    /*
     * Custom widget to concatenate first, middle and last names. Usage:
     * <widget type="concat_name_parts"/>
     */
    openerp.hr_extra.WidgetConCatCompleteName = openerp.web.form.FormWidget.extend({
        start : function() {
            this._super();
            this.field_manager.on("field_changed:firstname", this, this.concat_name_parts);
            this.field_manager.on("field_changed:middlename", this, this.concat_name_parts);
            this.field_manager.on("field_changed:lastname", this, this.concat_name_parts);
            this.concat_name_parts();
        },
        concat_name_parts : function() {
            var firstname = this.field_manager.get_field_value("firstname") || '';
            var middlename = this.field_manager.get_field_value("middlename") || '';
            var lastname = this.field_manager.get_field_value("lastname") || '';

            var remove_empty_strings = function(array) {
                for (var index = 0; index < array.length; index++) {
                    if (array[index] == '')
                        array.splice(index, 1);
                }
            };

            var names_parts = [ firstname, middlename, lastname ];
            remove_empty_strings(names_parts);
            var fullname = names_parts.join(' ');
            this.field_manager.set_values({'name' : fullname});
        },
    });
    openerp.web.form.custom_widgets.add('concat_name_parts', 'openerp.hr_extra.WidgetConCatCompleteName');
}

I think I have not misused the client side API but I might be wrong, I use the 'field_manager' attribute to listen name-part changes, read/concatenate their values and set the 'name' field.

Please provide some advice to get rid of this weird side effects and point any misusage of the client side API in my code.

Thanks in advance for looking at this.

0
Avatar
Discard
yom

you fix the fault thank you

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Sign up
Related Posts Replies Views Activity
Another TypeError: ClientWidget is null
web example clientwidget
Avatar
Avatar
1
Mar 15
9066
How to hide the default buttons in a popup window(defined by "ir.actions.client")
new target ir.actions popupwindow clientwidget
Avatar
1
Oct 24
1727
Is there any companent which can display the seats of a place like a stadium or a theator?
web chart webkit reactivate clientwidget
Avatar
0
Oct 24
1610
Community
  • Tutorials
  • Documentation
  • Forum
Open Source
  • Download
  • Github
  • Runbot
  • Translations
Services
  • Odoo.sh Hosting
  • Support
  • Upgrade
  • Custom Developments
  • Education
  • Find an Accountant
  • Find a Partner
  • Become a Partner
About us
  • Our company
  • Brand Assets
  • Contact us
  • Jobs
  • Events
  • Podcast
  • Blog
  • Customers
  • Legal • Privacy
  • Security
الْعَرَبيّة 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 is a suite of open source business apps that cover all your company needs: CRM, eCommerce, accounting, inventory, point of sale, project management, etc.

Odoo's unique value proposition is to be at the same time very easy to use and fully integrated.

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