Tùy chỉnh một field

Kế thừa một component field hiện có

Hãy lấy một ví dụ trong đó chúng ta muốn mở rộng BooleanField để tạo một field boolean hiển thị "Late!" bằng màu đỏ mỗi khi checkbox được đánh dấu.

  1. Tạo một component widget mới kế thừa component field mong muốn.

    late_order_boolean_field.js
    /** @odoo-module */
    
    import { registry } from "@web/core/registry";
    import { BooleanField } from "@web/views/fields/boolean/boolean_field";
    import { Component, xml } from "@odoo/owl";
    
    class LateOrderBooleanField extends BooleanField {}
    LateOrderBooleanField.template = "my_module.LateOrderBooleanField";
    
  2. Tạo template cho field.

    Component sử dụng một template mới có tên my_module.LateOrderBooleanField. Hãy tạo nó bằng cách kế thừa template hiện tại của BooleanField.

    late_order_boolean_field.xml
    <?xml version="1.0" encoding="UTF-8" ?>
    <templates xml:space="preserve">
        <t t-name="my_module.LateOrderBooleanField" t-inherit="web.BooleanField">
            <xpath expr="//CheckBox" position="after">
                  <span t-if="props.value" class="text-danger"> Late! </span>
            </xpath>
        </t>
    </templates>
    
  3. Đăng ký component vào registry của các field.

    late_order_boolean_field.js
    registry.category("fields").add("late_boolean", LateOrderBooleanField);
    
  4. Thêm widget trong arch của view như một thuộc tính của field.

    <field name="somefield" widget="late_boolean"/>
    

Tạo một component field mới

Giả sử chúng ta muốn tạo một field hiển thị một đoạn văn bản đơn giản bằng màu đỏ.

  1. Tạo một component Owl mới đại diện cho field mới của chúng ta

    my_text_field.js
    /** @odoo-module */
    
    import { standardFieldProps } from "@web/views/fields/standard_field_props";
    import { Component, xml } from "@odoo/owl";
    import { registry } from "@web/core/registry";
    
    export class MyTextField extends Component {
    
        /**
        * @param {boolean} newValue
        */
        onChange(newValue) {
            this.props.update(newValue);
        }
    }
    
    MyTextField.template = xml`
        <input t-att-id="props.id" class="text-danger" t-att-value="props.value" onChange.bind="onChange" />
    `;
    MyTextField.props = {
        ...standardFieldProps,
    };
    MyTextField.supportedTypes = ["char"];
    

    standardFieldProps được import chứa các prop chuẩn được View truyền vào, chẳng hạn như hàm update để cập nhật giá trị, type của field trong model, boolean readonly, và những thứ khác.

  2. Trong cùng file đó, đăng ký component vào registry của các field.

    my_text_field.js
    registry.category("fields").add("my_text_field", MyTextField);
    

    Điều này ánh xạ tên widget trong arch tới component thực tế của nó.

  3. Thêm widget trong arch của view như một thuộc tính của field.

    <field name="somefield" widget="my_text_field"/>