Tùy chỉnh một trường¶
Phân lớp một thành phần trường hiện có¶
Hãy lấy một ví dụ trong đó chúng tôi muốn mở rộng BooleanField
để tạo trường boolean hiển thị "Muộn!" màu đỏ bất cứ khi nào hộp kiểm được chọn.
Tạo thành phần tiện ích mới mở rộng thành phần trường 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";
Tạo mẫu trường.
Thành phần này sử dụng một mẫu mới có tên
my_module.LateOrderBooleanField
. Tạo nó bằng cách kế thừa mẫu hiện tại củaBooleanField
.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>
Đăng ký thành phần vào sổ đăng ký trường.
late_order_boolean_field.js
¶registry.category("fields").add("late_boolean", LateOrderBooleanField);
Thêm tiện ích trong vòm chế độ xem làm thuộc tính của trường.
<field name="somefield" widget="late_boolean"/>
Tạo một thành phần trường mới¶
Giả sử chúng ta muốn tạo một trường hiển thị văn bản đơn giản màu đỏ.
Tạo một thành phần Owl mới đại diện cho trường mới của chúng tôi
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
đã nhập chứa các đạo cụ tiêu chuẩn được truyền bởiView
chẳng hạn như hàmupdate
để cập nhật giá trị,loại
của trường trong mô hình, booleanchỉ đọc
và các giá trị khác.Trong cùng một tệp, đăng ký thành phần vào sổ đăng ký trường.
my_text_field.js
¶registry.category("fields").add("my_text_field", MyTextField);
Điều này ánh xạ tên tiện ích trong vòm tới thành phần thực tế của nó.
Thêm tiện ích trong vòm chế độ xem làm thuộc tính của trường.
<field name="somefield" widget="my_text_field"/>