In this blog, we can see how to make a float to int widget in Odoo 17.
We can create a new custom widget in Odoo 17 that can be added to every field that requires this function. The main use of the float to int widget is that it will convert the float value given into its nearest int value.
Eg
12.6 => 13
12.2 => 12
In order to create a custom widget, you can use the following steps:
Create an xml in static/src/xml/float_int.xml
<?xml version="1.0" encoding="UTF-8" ?>
<templates id="template" xml:space="preserve">
<t t-name="float_int_widget.FloatIntField">
<input type="number" class="o_input flex-grow-1 flex-shrink-1" t-ref="inputfloatint"/>
</t>
</templates>
This is the template given where the input for the widget is given, and the value given in the widget is taken into the js.
Corresponding js function is created in static/src/js/float_int.js
/** @odoo-module **/
import { registry } from "@web/core/registry";
import { useInputField } from "@web/views/fields/input_field_hook";
import { standardFieldProps } from "@web/views/fields/standard_field_props";
import { onRendered } from "@odoo/owl";
import {Component, useState} from "@odoo/owl";
import { useRef, useEffect, onWillRender, onMounted } from "@odoo/owl";
import { parseFloat } from "@web/views/fields/parsers";
export class FloatInt extends Component{
static template = "float_int_widget.FloatIntField";
setup(){
this.input = useRef('inputfloatint')
useInputField({ getValue: () => this.props.record.data[this.props.name] || "" ,
refName: "inputfloatint",parse: (v) => parseFloat(v),});
onWillRender(() => {
this.rounded()
});
onMounted(() => {
this.rounded()
});
}
rounded(){
if (this.input.el)
{
this.props.record.data[this.props.name] = Math.round(this.input.el.value)
}
}
}
FloatInt.component = FloatInt
FloatInt.supportedTypes = ["float"]
registry.category("fields").add("float_int_widget", FloatInt);
Since we have given tref in the input, we can access values from the input into the JS.
Rounded()
This is the main function where the input Float value is converted into its nearest int value.
Add float_int_widget into registry.
Next we need to add the widget into a field where we need the widget.
Eg:
<field name="float_int" widget="float_int_widget"/>
After this process, we need to add the js and xml to the manifest.
'data':
[
'views/res_partner.xml',
],
'assets':
{
'web.assets_backend':
{
'float_int_widget/static/src/js/float_int.js',
'float_int_widget/static/src/xml/float_int.xml',
},
},
We added the field in views/res_partner.xml.
In web.assets_backend we have added the js and xml.
Now you can see how the custom created widget works.
To read more about Field Types and Widgets in Odoo 16, refer to our blog Field Types and Widgets in Odoo 16.