This question has been flagged
5125 Views

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.

Avatar
Discard

you fix the fault thank you