Views¶
Views are what define how records should be displayed to end-users. They are specified in XML which means that they can be edited independently from the models that they represent. They are flexible and allow a high level of customization of the screens that they control. There exist various types of views. Each of them represents a mode of visualization: form, list, kanban, etc.
Generic structure¶
Basic views generally share the common structure defined below. Placeholders are denoted in all caps.
<record id="MODEL_view_TYPE" model="ir.ui.view">
<field name="name">NAME</field>
<field name="model">MODEL</field>
<field name="arch" type="xml">
<VIEW_TYPE>
<VIEW_SPECIFICATIONS/>
</VIEW_TYPE>
</field>
</record>
Fields¶
View objects expose a number of fields. They are optional unless specified otherwise.
name(mandatory)CharOnly useful as a mnemonic/description of the view when looking for one in a list of some sort.
modelCharThe model linked to the view, if applicable.
priorityIntegerWhen a view is requested by
(model, type), the view matching the model and the type, with the lowest priority will be returned (it is the default view).It also defines the order of views application during view inheritance.
groups_idMany2many->odoo.addons.base.models.res_users.GroupsThe groups allowed to use/access the current view.
If the view extends an existing view, the extension will only be applied for a given user if the user has access to the provided
groups_id.archTextThe description of the view layout.
Attributes¶
The different view types have a wide variety of attributes allowing customizations of the generic behaviors. Some main attributes will be explained here. They do not all have an impact on all view types.
Note
The current context and user access rights may also impact the view abilities.
createDisable/enable record creation on the view.
edit(form&list&gantt)Disable/enable record editing on the view.
delete(form&list)Disable/enable record deletion on the view through the Action dropdown.
duplicate(form)Disable/enable record duplication on the view through the Action dropdown.
decoration-{$name}(list&gantt)Define a conditional display of a record in the style of a rowâs text based on the corresponding recordâs attributes.
Values are Python expressions. For each record, the expression is evaluated with the recordâs attributes as context values and if
true, the corresponding style is applied to the row. Here are some of the other values available in the context:uid: the id of the current user,today: the current local date as a string of the formYYYY-MM-DD,now: same astodaywith the addition of the current time. This value is formatted asYYYY-MM-DD hh:mm:ss.
<tree decoration-info="state == 'draft'" decoration-danger="state == 'help_needed'" decoration-bf="state='busy'"> <!-- TREE_VIEW_CONTENT --> </tree>
Warning
Supported values differ for the two view types. The Gantt view only supports
success,info,warning,dangerandsecondarydisplays. The list view supportsbf,it,success,info,warning,danger,mutedandprimarydisplays.sample(kanban&list&gantt&graph&pivot&cohort)Populate the view with a set of sample records if none are found for the current model. This attribute is false by default.
These fake records will have heuristics for certain field names/models. For example, a field âdisplay_nameâ on the model âres.usersâ will be populated with sample people names while an âemailâ field will be in the form âfirstname.lastname@sample.demoâ.
The user will not be able to interact with these data and they will be discarded as soon as an action is performed (record created, column added, etc.)
banner_routea route address to be fetched and prepended to the view.If this attribute is set, the controller route url will be fetched and displayed above the view. The json response from the controller should contain an âhtmlâ key.
If the html contains a stylesheet <link> tag, it will be removed and appended to <head>.
To interact with the backend you can use <a type=âactionâ> tags. Please take a look at the documentation of the _onActionClicked method of AbstractController (addons/web/static/src/js/views/abstract_controller.js) for more details.
Only views extending AbstractView and AbstractController can use this attribute, like Form, Kanban, List, âŠ
Example:
<tree banner_route="/module_name/hello" />
class MyController(odoo.http.Controller): @http.route('/module_name/hello', auth='user', type='json') def hello(self): return { 'html': """ <div> <link href="/module_name/static/src/css/banner.css" rel="stylesheet"> <h1>hello, world</h1> </div> """ }
classoptional string containing some classes to set on the root node of the view.js_classoptional component class to use to render the view. If set, thejs_classattribute will also be used to apply a css class to the root node of the view. For example, ifjs_classis set tomy-custom-kanban, then the classo_my-custom-kanban_viewwill be applied on the root node.
Inheritance¶
Inheritance fields¶
The two following View fields are used to specify
inherited views.
inherit_idMany2onethe current viewâs parent view, unset by default. Specify the parent using the
refattribute:<field name="inherit_id" ref="library.view_book_form"/>
modeSelection:extension / primaryinheritance mode,
extensionby default ifinherit_idis set,primaryotherwise.An example of where you would want to override
modewhile usinginherit_idis delegation inheritance. In that case your derived model will be separate from its parent and views matching with one wonât match with the other. Suppose you inherit from a view associated with the parent model and want to customize the derived view to show data from the derived model. Themodeof the derived view needs to be set toprimary, because itâs the base (and maybe only) view for that derived model. Otherwise the view matching rules wonât apply.
View matching¶
if a view is requested by
(model, type), the view with the right model and type,mode=primaryand the lowest priority is matched.when a view is requested by
id, if its mode is notprimaryits closest parent with modeprimaryis matched.
View resolution¶
Resolution generates the final arch for a requested/matched primary
view:
if the view has a parent, the parent is fully resolved then the current viewâs inheritance specs are applied
if the view has no parent, its
archis used as-isthe current viewâs children with mode
extensionare looked up and their inheritance specs are applied depth-first (a child view is applied, then its children, then its siblings)
The result of applying children views yields the final arch
Inheritance specs¶
Inheritance specs are comprised of an element locator, to match the inherited element in the parent view, and children element that will be used to modify the inherited element.
There are three types of element locators for matching a target element:
An
xpathelement with anexprattribute.expris an XPath expression1 applied to the currentarch, the first node it finds is the matcha
fieldelement with anameattribute, matches the firstfieldwith the samename. All other attributes are ignored during matchingany other element: the first element with the same name and identical attributes (ignoring
positionandversionattributes) is matched
<xpath expr="page[@name='pg']/group[@name='gp']/field" position="inside">
<field name="description"/>
</xpath>
<field name="res_id" position="after"/>
<div name="name" position="replace">
<div name="name2">
<field name="name2"/>
</div>
</div>
The inheritance spec may have an optional position attribute specifying
how the matched node should be altered:
inside(default)the content of the inheritance spec is appended to the matched node
replacethe content of the inheritance spec replaces the matched node. Any text node containing only
$0within the contents of the spec will be replaced by a complete copy of the matched node, effectively wrapping the matched node.afterthe content of the inheritance spec is added to the matched nodeâs parent, after the matched node
beforethe content of the inheritance spec is added to the matched nodeâs parent, before the matched node
attributesthe content of the inheritance spec should be
attributeelements with anameattribute and an optional body:if the
attributeelement has a body, a new attributed named after itsnameis created on the matched node with theattributeelementâs text as valueif the
attributeelement has no body, the attribute named after itsnameis removed from the matched node. If no such attribute exists, an error is raisedif the
attributeelement has anaddattribute, aremoveattribute, or both, the value of the matched nodeâs attribute named afternameis recomputed to include the value(s) ofadd(separated byseparator) and delete the value(s) ofremove(separated byseparator). Ifseparatoris not provided,,is used instead.
<field name="sale_information" position="attributes"> <attribute name="invisible">0</attribute> <attribute name="attrs"> {'invisible': [('sale_ok', '=', False)], 'readonly': [('editable', '=', False)]} </attribute> <attribute name="class" add="mt-1 mb-1" remove="mt-2 mb-2" separator=" "/> </field>
movecan be used as a direct child of a inheritance spec with a
inside,replace,afterorbeforepositionattribute to move a node.<xpath expr="//@target" position="after"> <xpath expr="//@node" position="move"/> </xpath> <field name="target_field" position="after"> <field name="my_field" position="move"/> </field>
A viewâs specs are applied sequentially.
- 1
an extension function is added for simpler matching in QWeb views:
hasclass(*classes)matches if the context node has all the specified classes
Model Commons¶
Attributes¶
- Model._date_name = 'date'¶
field to use for default calendar view
Methods¶
- Model.get_views(views, options=None)[source]¶
Returns the fields_views of given views, along with the fields of the current model, and optionally its filters for the given action.
- Parameters
views â list of [view_id, view_type]
options (dict) â
a dict optional boolean flags, set to enable:
toolbarincludes contextual actions when loading fields_views
load_filtersreturns the modelâs filters
action_idid of the action to get the filters, otherwise loads the global filters or the model
- Returns
dictionary with fields_views, fields and optionally filters
- Model.get_view([view_id | view_type='form'])[source]¶
Get the detailed composition of the requested view like model, view architecture
- Parameters
view_id (int) â id of the view or None
view_type (str) â type of the view to return if view_id is None (âformâ, âtreeâ, âŠ)
options (dict) â boolean options to return additional features: - bool mobile: true if the web client is currently using the responsive mobile view (to use kanban views instead of list views for x2many fields)
- Returns
composition of the requested view (including inherited views and extensions)
- Return type
- Raises
AttributeError â
if the inherited view has unknown position to work with other than âbeforeâ, âafterâ, âinsideâ, âreplaceâ
if some tag other than âpositionâ is found in parent view
Invalid ArchitectureError â if there is view type other than form, tree, calendar, search etc⊠defined on the structure
View types¶
Activity¶
The Activity view is used to display the activities linked to the records. The
data are displayed in a chart with the records forming the rows and the activity
types the columns. The first cell of each row displays a (customizable, see
templates, quite similarly to Kanban) card representing
the corresponding record. When clicking on others cells, a detailed description
of all activities of the same type for the record is displayed.
Warning
The Activity view is only available when the mail module is installed,
and for the models that inherit from the mail.activity.mixin.
The root element of the Activity view is <activity>, it accepts the following
attributes:
string(mandatory)A title, which should describe the view
Possible children of the view element are:
fielddeclares fields to use in activity logic. If the field is simply displayed in the activity view, it does not need to be pre-declared.
Possible attributes are:
name(required)the name of the field to fetch
templatesdefines the QWeb Templates templates. Cards definition may be split into multiple templates for clarity, but activity views must define at least one root template
activity-box, which will be rendered once for each record.The activity view uses mostly-standard javascript qweb and provides the following context variables (see Kanban for more details):
widgetthe current
ActivityRecord(), can be used to fetch some meta-information. These methods are also available directly in the template context and donât need to be accessed viawidgetrecordan object with all the requested fields as its attributes. Each field has two attributes
valueandraw_value
Calendar¶
Calendar views display records as events in a daily, weekly, monthly or yearly calendar.
Note
By default the calendar view will be centered around the current date
(today). You can pass a specific initial date to the context of the action in
order to set the initial focus of the calendar on the period (see mode) around
this date (the context key to use being initial_date)
Their root element is <calendar>. Available attributes on the
calendar view are:
date_start(required)name of the recordâs field holding the start date for the event
date_stopname of the recordâs field holding the end date for the event, if
date_stopis provided records become movable (via drag and drop) directly in the calendardate_delayalternative to
date_stop, provides the duration of the event instead of its end date (unit: day)colorname of a record field to use for color segmentation. Records in the same color segment are allocated the same highlight color in the calendar, colors are allocated semi-randomly. Displayed the display_name/avatar of the visible record in the sidebar
form_view_idview to open when the user create or edit an event. Note that if this attribute is not set, the calendar view will fall back to the id of the form view in the current action, if any.
event_open_popupIf the option âevent_open_popupâ is set to true, then the calendar view will open events (or records) in a FormViewDialog. Otherwise, it will open events in a new form view (with a do_action)
quick_addWhen a boolean value is passed, enables quick-event creation on click: only asks the user for a
name(the field to which this values is saved can be controlled throughrec_name) and tries to create a new event with just that and the clicked event time. Falls back to a full form dialog if the quick creation fails. This attribute also accepts a form view id, which will be used instead of the quick create default dialog.create_name_fieldname of the recordâs field holding the textual representation of the record, this is used when creating records through the âquick createâ mechanism
all_dayname of a boolean field on the record indicating whether the corresponding event is flagged as day-long (and duration is irrelevant)
modeDefault display mode when loading the calendar. Possible attributes are:
day,week,month,yearscalesComma-separated list of scales to provide. By default, all scales are available. See mode for possible scale values.
create,deleteallows disabling the corresponding action in the view by setting the corresponding attribute to
false<field>declares fields to aggregate or to use in kanban logic. If the field is simply displayed in the calendar cards.
Fields can have additional attributes:
invisibleuse âTrueâ to hide the value in the cards
avatar_fieldonly for x2many field, to display the avatar instead of the display_name in the cards
write_modelandwrite_fieldandfilter_fieldyou can add a filter and save the result in the defined model, the filter is added in the sidebar. The
filter_fieldis optional and allows you to specify the field that will hold the status of the filter.filtersandcoloruse âTrueâ to add this field in filter in the sidebar. You can specify a
colorfield used to colorize the checkbox.
Cohort¶
Enterprise featureThe cohort view is used to display and understand the way some data changes over a period of time. For example, imagine that for a given business, clients can subscribe to some service. The cohort view can then display the total number of subscriptions each month, and study the rate at which client leave the service (churn). When clicking on a cell, the cohort view will redirect you to a new action in which you will only see the records contained in the cellâs time interval; this action contains a list view and a form view.
Note
By default the cohort view will use the same list and form views as those
defined on the action. You can pass a list view and a form view
to the context of the action in order to set/override the views that will be
used (the context keys to use being form_view_id and list_view_id)
For example, here is a very simple cohort view:
<cohort string="Subscription" date_start="date_start" date_stop="date" interval="month"/>
The root element of the Cohort view is <cohort>, it accepts the following attributes:
string(mandatory)A title, which should describe the view
date_start(mandatory)A valid date or datetime field. This field is understood by the view as the beginning date of a record
date_stop(mandatory)A valid date or datetime field. This field is understood by the view as the end date of a record. This is the field that will determine the churn.
disable_linking(optional)Set to
1to prevent from redirecting clicks on cohort cells to list view.mode(optional)A string to describe the mode. It should be either âchurnâ or âretentionâ (default). Churn mode will start at 0% and accumulate over time whereas retention will start at 100% and decrease over time.
timeline(optional)A string to describe the timeline. It should be either âbackwardâ or âforwardâ (default). Forward timeline will display data from date_start to date_stop, whereas backward timeline will display data from date_stop to date_start (when the date_start is in future / greater than date_stop).
interval(optional)A string to describe a time interval. It should be âdayâ, âweekâ, âmonthââ (default) or âyearâ.
measure(optional)A field that can be aggregated. This field will be used to compute the values for each cell. If not set, the cohort view will count the number of occurrences.
<field>(optional)allows to specify a particular field in order to manage it from the available measures, itâs main use is for hiding a field from the selectable measures:
name(mandatory)the name of the field to use in the view.
string(optional)the name that would be used to display the field in the cohort view, overrides the default python String attribute of the field.
invisible(optional)if true, the field will not appear either in the active measures nor in the selectable measures (useful for fields that do not make sense aggregated, such as fields in different units, e.g. ⏠and $).
Form¶
Form views are used to display the data from a single record. Their root
element is <form>. They are composed of regular HTML with additional
structural and semantic components.
Structural components¶
Structural components provide structure or âvisualâ features with little logic. They are used as elements or sets of elements in form views.
notebookdefines a tabbed section. Each tab is defined through a
pagechild element. Pages can have the following attributes:string(required)the title of the tab
accesskeyan HTML accesskey
attrsstandard dynamic attributes based on record values
Note
Note that
notebookshould not be placed withingroupgroupused to define column layouts in forms. By default, groups define 2 columns and most direct children of groups take a single column.
fielddirect children of groups display a label by default, and the label and the field itself have a colspan of 1 each.The number of columns in a
groupcan be customized using thecolattribute, the number of columns taken by an element can be customized usingcolspan.Children are laid out horizontally (tries to fill the next column before changing row).
Groups can have a
stringattribute, which is displayed as the groupâs titlenewlineonly useful within
groupelements, ends the current row early and immediately switches to a new row (without filling any remaining column beforehand)separatorsmall horizontal spacing, with a
stringattribute behaves as a section titlesheetcan be used as a direct child to
formfor a narrower and more responsive form layoutheadercombined with
sheet, provides a full-width location above the sheet itself, generally used to display workflow buttons and status widgets
Semantic components¶
Semantic components tie into and allow interaction with the Odoo system. Available semantic components are:
buttoncall into the Odoo system, similar to list view buttons. In addition, the following attribute can be specified:
specialfor form views opened in dialogs:
saveto save the record and close the dialog,cancelto close the dialog without saving.confirmconfirmation message to display (and for the user to accept) before performing the buttonâs Odoo call (also works in Kanban views).
fieldrenders (and allow editing of, possibly) a single field of the current record. Using several times a field in a form view is supported and the fields can receive different values for modifiers âinvisibleâ and âreadonlyâ. However, the behavior is not guaranteed when several fields exist with different values for modifier ârequiredâ. Possible attributes of the field node are:
name(mandatory)the name of the field to render
idthe node id. Useful when there are several occurrences of the same field in the view (see
labelcomponent below). Default is the field name.widgetfields have a default rendering based on their type (e.g.
Char,Many2one). Thewidgetattributes allows using a different rendering method and context.optionsJSON object specifying configuration option for the fieldâs widget (including default widgets)
classHTML class to set on the generated element, common field classes are:
oe_inlineprevent the usual line break following fields and limit their span.
oe_left,oe_rightfloats the field to the corresponding direction
oe_read_only,oe_edit_onlyonly displays the field in the corresponding form mode
oe_avatarfor image fields, displays images as âavatarâ (square, 90x90 maximum size, some image decorations)
groupsonly displays the field for specific users
on_changecalls the specified method when this fieldâs value is edited, can generate update other fields or display warnings for the user
Deprecated since version 8.0: Use
odoo.api.onchange()on the modelattrsdynamic meta-parameters based on record values
domainfor relational fields only, filters to apply when displaying existing records for selection
contextfor relational fields only, context to pass when fetching possible values
readonlydisplay the field in both readonly and edit mode, but never make it editable
requiredgenerates an error and prevents saving the record if the field doesnât have a value
nolabeldonât automatically display the fieldâs label, only makes sense if the field is a direct child of a
groupelementplaceholderhelp message to display in empty fields. Can replace field labels in complex forms. Should not be an example of data as users are liable to confuse placeholder text with filled fields
modefor
One2many, display mode (view type) to use for the fieldâs linked records. One oftree,form,kanbanorgraph. The default istree(a list display)helptooltip displayed for users when hovering the field or its label
filenamefor binary fields, name of the related field providing the name of the file
passwordindicates that a
Charfield stores a password and that its data shouldnât be displayedkanban_view_reffor opening specific kanban view when selecting records from m2o/m2m in mobile environment
labelwhen a
fieldcomponent isnât placed directly inside agroup, or when itsnolabelattribute is set, the fieldâs label isnât automatically displayed alongside its value. Thelabelcomponent is the manual alternative of displaying the label of a field. Possible attributes are:for(mandatory)the reference to the field associated with the label. Can be either the name of a field, or its id (
idattribute set on thefield). When there are several occurrences of the same field in the view, and there are severallabelcomponents associated with thesefieldnodes, those labels must have uniqueforattributes (in this case referencing theidattribute of the correspondingfieldnodes).stringthe label to display. Display the fieldâs label (coming from the field definition in the model) by default.
classsame as for
fieldcomponent.attrssame as for
fieldcomponent.
settingThe
settingtag is used to declare a setting, an entity visually separated on two panels (left and right), and used to edit a given field. The first field in the setting is used as the main field (optional). This field is placed on the left panel (if itâs a boolean field) or on the top of the right panel (otherwise). The field is also used to create the setting label if astringis not defined. Thesettingtag can also contain more elements (e.g. html), all of these elements are rendered in the right panel.string(optional)The text used as label of the setting. If itâs not defined, the first field is used as label.
title(optional)The text used as tooltip.
help(optional)The help/description of the setting. This text is displayed just below the setting label (with classname
text-muted).company_dependent(optional)If this attribute is set to â1â an icon is displayed next to the setting label to explicit that this setting is company-specific.
documentation(optional)If this attribute is set, an icon is added next to the setting label, this icon is a link to the documentation. Note that you can use relative or absolute path. The relative path is relative to
https://www.odoo.com/documentation/<server_version>, so itâs not necessary to hard-code the server version on the arch anymore.
Example
<setting string="this is bar"> <field name="bar"/> ...More elements </setting>
Generic structure¶
<form>
<header>
<field name="state" widget="statusbar"/>
</header>
<sheet>
<div class="oe_button_box">
<BUTTONS/>
</div>
<group>
<group>
<field name="fname"/>
</group>
</group>
<notebook>
<page string="Page1">
<group>
<CONTENT/>
</group>
</page>
<page string="Page2">
<group>
<CONTENT/>
</group>
</page>
</notebook>
</sheet>
</form>
Settings Form View¶
The settings form view is a customization of the form view. Itâs used to centralize all the settings of Odoo.
This view differs from a generic form view because it has a search bar, a sidebar and accepts 2
additional tags: app and block. It also adds a new parameter to the setting tag.
appThe
apptag is used to declare the application on the settings view. It creates an entry with its logo on the sidebar of the view. It also acts as delimiter when searching.Syntax:
<app string="CRM" name="crm"> ... </app>
Parameters:
stringThe âdisplayâ name of the application.
nameThe technical name of the application (the name of the module).
logo(optional)The relative path to the logo. If not set, the logo is created using the
nameparameter :/{name}/static/description/icon.png.
blockThe
blocktag is used to declare a group of settings. This group can have a title and a description/help.Syntax:
<block title="Title of group Bar"> ... </block>
Parameters:
title(optional)The title of the block of settings, you can perform research on its text.
help(optional)The description/help of the block of settings, you can perform research on its text.
settingThe definition and all the available parameters of the
settingtag can be found in the setting tag definition in the form view. The settings form view adds the following parameter to thesettingtag:type(optional)By default, a setting is visually separated on two panels (left and right), and is used to edit a given field. By defining
type='header', a special kind of setting is rendered instead. This setting is used to modify the scope of the other settings. For example, on the website application, this setting is used to indicate to which website the other settings apply. The header setting is visually represented as a yellow banner on the top of the screen.
Example
<app string="CRM" name="crm">
<setting type="header" string="Foo">
<field name="foo" title="Foo?."/>
<button name="nameAction" type="object" string="Button"/>
</setting>
<block title="Title of group Bar">
<setting help="this is bar" documentation="/applications/technical/web/settings/this_is_a_test.html">
<field name="bar"/>
</setting>
<setting string="This is Big BAR" company_specific="1">
<field name="bar"/>
</setting>
</block>
<block title="Title of group Foo">
<setting string="Personalize setting" help="this is full personalize setting">
<div>This is a different setting</div>
</setting>
</block>
</app>
Gantt¶
Enterprise featureGantt views appropriately display Gantt charts (for scheduling).
The root element of gantt views is <gantt/>, it has no children but can
take the following attributes:
date_start(required)name of the field providing the start datetime of the event for each record.
date_stop(required)name of the field providing the end duration of the event for each record.
dependency_fieldname of the
many2manyfield that provides the dependency relation between two records. If B depends on A,dependency_fieldis the field that allows getting A from B. Both this field anddependency_inverted_fieldfield are used to draw dependency arrows between pills and reschedule them.dependency_inverted_field(required ifdependency_fieldis provided)name of the
many2manyfield that provides the invert dependency relation thandependency_field. If B depends on A,dependency_inverted_fieldis the field that allows getting B from A.colorname of the field used to color the pills according to its value
decoration-{$name}allow changing the style of a rowâs text based on the corresponding recordâs attributes.
Values are Python expressions. For each record, the expression is evaluated with the recordâs attributes as context values and if
true, the corresponding style is applied to the row. Here are some of the other values available in the context:uid: the id of the current user,today: the current local date as a string of the formYYYY-MM-DD,now: same astodaywith the addition of the current time. This value is formatted asYYYY-MM-DD hh:mm:ss.
{$name}can be one of the following bootstrap contextual color (danger,info,secondary,successorwarning).default_group_byname of a field to group tasks by
disable_drag_dropif set to true, the gantt view will not have any drag&drop support
consolidationfield name to display consolidation value in record cell
consolidation_maxdictionary with the âgroup byâ field as key and the maximum consolidation value that can be reached before displaying the cell in red (e.g.
{"user_id": 100})consolidation_excludename of the field that describes if the task has to be excluded from the consolidation if set to true it displays a striped zone in the consolidation line
create,cell_create,edit,delete,planallows disabling the corresponding action in the view by setting the corresponding attribute to
false(default:true).create: If enabled, anAddbutton will be available in the control panel to create records.cell_create: If enabled andcreateenabled, a â+â button will be displayed while hovering on a time slot cell to create a new record on that slot.edit: If enabled, the opened records will be in edit mode (thus editable).plan: If enabled andeditenabled, a âmagnifying glassâ button will be displayed on time slots to plan unassigned records into that time slot.
Example
When you do not want to create records on the gantt view and the beginning and end dates are required on the model, the planning feature should be disabled because no record will ever be found.
offsetDepending on the scale, the number of units to add to today to compute the default period. Examples: An offset of +1 in default_scale week will open the gantt view for next week, and an offset of -2 in default_scale month will open the gantt view of 2 months ago.
progressname of a field providing the completion percentage for the recordâs event, between 0 and 100
stringtitle of the gantt view
precisionJSON object specifying snapping precisions for the pills in each scale.
Possible values for scale
dayare (default:hour):hour: records times snap to full hours (ex: 7:12 becomes 8:00)hour:half: records times snap to half hours (ex: 7:12 becomes 7:30)hour:quarter: records times snap to half hours (ex: 7:12 becomes 7:15)
Possible values for scale
weekare (default:day:half):day: records times snap to full days (ex: 7:28 AM becomes 11:59:59 PM of the previous day, 10:32 PM becomes 12:00 PM of the current day)day:half: records times snap to half hours (ex: 7:28 AM becomes 12:00 PM)
Possible values for scale
monthare (default:day:half):day: records times snap to full days (ex: 7:28 AM becomes 11:59:59 PM of the previous day, 10:32 PM becomes 12:00 PM of the current day)day:half: records times snap to half hours (ex: 7:28 AM becomes 12:00 PM)
Scale
yearalways snap to full day.Example of precision attribute:
{"day": "hour:quarter", "week": "day:half", "month": "day"}total_rowboolean to control whether the row containing the total count of records should be displayed. (default:
false)display_unavailabilityboolean to mark the dates returned by the
gantt_unavailabilityfunction of the model as available inside the gantt view. Records can still be scheduled in them, but their unavailability is visually displayed. (default:false)default_scaledefault scale when rendering the view. Possible values are (default:
month):dayweekmonthyear
scalescomma-separated list of allowed scales for this view. By default, all scales are allowed. For possible scale values to use in this list, see
default_scale.templatesdefines the QWeb template
gantt-popoverwhich is used by the popover that is opened when the user clicks on a record in the gantt view.on_createIf specified, launch a client action when clicking the add button on the view instead of opening a generic dialog. This should hold the xmlid of the action (eg:
on_create="%(my_module.my_wizard)d").form_view_idview to open when the user create or edit a record. Note that if this attribute is not set, the gantt view will fall back to the id of the form view in the current action, if any.
dynamic_rangeif set to true, the gantt view will start at the first record, instead of starting at the beginning of the year/month/day.
pill_labelIf set to true, the time appears in the pill label when the scale is set on week or month. (e.g.
7:00 AM - 11:00 AM (4h) - DST Task 1)thumbnailsThis allows to display a thumbnail next to groups name if the group is a relationnal field. This expects a python dict which keys are the name of the field on the active model. Values are the names of the field holding the thumbnail on the related model.
Example: tasks have a field user_id that reference res.users. The res.users model has a field image that holds the avatar, then:
<gantt date_start="date_start" date_stop="date_stop" thumbnails="{'user_id': 'image_128'}" > </gantt>
will display the users avatars next to their names when grouped by user_id.
Graph¶
The graph view is used to visualize aggregations over a number of records or
record groups. Its root element is <graph> which can take the following
attributes:
type(optional)one of
bar(default),pieandline, the type of graph to usestacked(optional)only used for
barcharts. Set to0to prevent the bars within a group to be stacked initially.disable_linking(optional)set to
1to prevent from redirecting clicks on graph to list vieworder(optional)if set, x-axis values will be sorted by default according their measure with respect to the given order (
ascordesc). Only used forbarandpiecharts.string(optional)string displayed in the breadcrumbs when redirecting to list view.
The only allowed element within a graph view is field which can have the
following attributes:
name(mandatory)the name of a field to use in the view. If used for grouping (rather than aggregating)
invisible(optional)if true, the field will not appear either in the active measures nor in the selectable measures.
type(optional)if set to
measure, the field will be used as an aggregated value within a group instead of a grouping criteria. It only works for the last field with that attribute but it is useful for other fields with string attribute (see below).interval(optional)on date and datetime fields, groups by the specified interval (
day,week,month,quarteroryear) instead of grouping on the specific datetime (fixed second resolution) or date (fixed day resolution). Default ismonth.string(optional)only used for field with
type="measure". The name that will be used to display the field in the graph view, overrides the default python String attribute of the field.
The measures are automatically generated from the model fields; only the aggregatable fields are used. Those measures are also alphabetically sorted on the string of the field.
Warning
graph view aggregations are performed on database content, non-stored function fields can not be used in graph views
Grid¶
Enterprise featureLimitations¶
This view is a work in progress and may have to be expanded or altered.
only
datecolumn fields have been tested,selectionandmany2oneare nominally implemented and supported but have not been tested,datetimeis not implemented at all.column cells are hardly configurable and must be numerical
cell adjustment is disabled by default and must be configured to be enabled
create,editanddeleteACL metadata doesnât get automatically set on the view root due to limitations infields_view_getpost-processing (thereâs a fixed explicit list of the view types getting those attributes)
Schema¶
The grid view has its own schema and additional validation in this module. The view architecture is:
<grid>(1)architecture root element
mandatory
stringattributeoptional
create,editanddeleteattributesoptional
adjustmentandadjust_nameattributesadjustmentcan be eitherobjectoractionto indicate whether a cellâs adjustment should be performed through a method call or an action execution.adjust_nameprovides respectively the method name and the action id.In both cases, the adjustment parameters are provided as a
grid_adjustcontext member, in theobjectcase, the parameters are also provided as positional function parameters (next to an empty list of ids):row_domainthe domain matching the entire row of the adjusted cell
column_fieldthe name of the column for the adjusted cell
column_valuethe value of the column for the adjusted cell
cell_fieldthe measure field of the adjusted cell
changethe difference between the old value of the cell and the adjusted one, may be positive or negative
optional
hide_line_totalandhide_column_totalattributeshide_line_totalset to true to hide total line (default false)
hide_column_totalset to true to hide total column (default false)
optional
barchart_totalattributebarchart_totalset to
truein order to display a bar chart at the bottom of the grid, based on the totals of the columns (default false).
optional
create_inlineanddisplay_emptyattributescreate_inlineset to
truein order to display an additional row at bottom of the grid with anAdd a linebutton (default false). When this option is set totrue, theAdd a linebutton from the control panel is hidden. When no data is available and whendisplay_emptyis not set (so when the help content is displayed), the theAdd a linebutton from the control panel is shown in order to let the user create a first record.display_emptyset to
truein order to keep displaying the grid when there is no data (default false). This can be useful when you want the user to be able to keep track of the current period (as dates are displayed in the columns headers). As a reminder, when no data are present and when this attribute is no set, the help content is displayed instead of the grid.
<button>(0+)Regular Odoo action buttons, displayed in the view header
mandatory
stringattribute (the button label)mandatory
typeattribute, eitherobjectoractionNote
workflow buttons are not supported
mandatory
nameattribute, either the name of the method to call, or the ID of the action to executeoptional
context
The server callback is provided with all the record ids displayed in the view, either as the ids passed to the method (
objectbutton) or as the contextâsactive_ids(actionbuttons)<field type="row">(1+)Row grouping fields, will be replaced by the search viewâs groupby filter if any.
The order of
rowfields in the view provides their grouping depth: if the first field isschooland the second isagethe records will be grouped byschoolfirst and byagewithin each school.<field type="col">(1)Column grouping field.
The col field can contain 0+
<range>elements which specify customisable column ranges.rangeelements have the following mandatory attributesnamecan be used to override the default range (the first one by default) through the
grid_rangecontext valuestringthe range buttonâs label (user-visible)
spansymbolic name of the span of all columns to display at once in the view, may trigger pagination.
For
datefields, valid spans are currentlyweekandmonth.stepsymbolic name of the step between one column and the previous/next
For
datefields, the only valid span is currentlyday.
<field type="measure">(1)Cell field, automatically accumulated (by
read_group).The measure field can take a
widgetattribute to customise its display.
Server interactions¶
Aside from optional buttons, the grid view currently calls two methods:
read_grid(provided on all models by the module) returns almost the entirety of the gridâs content as a dict:the row titles is a list of dictionaries with the following keys:
values(required)this maps to a dictionary with a key per
rowfield, the values are always of the form[value, label].domain(required)the domain of any record at the source of this row, in case itâs necessary to copy a record during cell adjustment
the column titles is a list of dictionaries with at least one key:
values(required)see row title values
domain(required)see column domain value
current(optional)boolean, marks/highlights a column
the grid data as a list (of rows) of list (of cells) of cell dicts each with the following keys:
valuethe numeric value associated with the cell
domainthe domain matching the cellâs records (should be assumed opaque)
sizethe number of records grouped in the cell
readonly(optional)a boolean indicating that this specific cell should not be client-editable
classes(optional)a list of classes (as strings) to add on the cellâs container (between the cellâs TD and the cellâs potentially-editable element).
In case of conflicts between this list and the base classes (prefixed with
o_grid_cell_), the classes in this list are ignored.
Note that the grid data is dense, if querying the database yields no group matching a cell a cell will generate an âemptyâ cell with default values for required keys.
prevandnextwhich can be either falsy (no pagination) or a context item to merge into the viewâs own context toread_gridthe previous or next page, it should be assumed to be opaque
read_grid_domain(field, range)(provided on al models by the module) returns the domain matching the current configured âspanâ of the grid. This is also done internally byread_grid, but can be useful or necessary to call independently to use with separate e.g.search_countorread_group.adjust_grid, for which there currently isnât a blanket implementation and whose semantics are likely to evolve with time and use cases
Server Hooks¶
read_grid calls a number of hooks allowing the customisation of its
operations from within without having to override the entire method:
_grid_format_cell(group, cell_field)converts the output of a read_group (group-by-group) into cells in the format described above (as part of âthe grid dataâ)
_grid_make_empty_cell(row_domain, column_domain, view_domain)generates an empty version of a cell (if there is no corresponding group)
_grid_column_info(name, range)generates a ColumnMetadata object based on the column type, storing values either returned directly (as part of
read_grid) or used query and reformatread_groupintoread_grid:groupingthe actual grouping field/query for the columns
domaindomain to apply to
read_groupin case the column field is paginated, can be an empty listprevandnextcontext segments which will be sent to
read_gridfor pages before and after the current one. IfFalse, disables pagination in that directionvaluescolumn values to display on the âcurrent pageâ, each value is a dictionary with the following keys:
valuesdictionary mapping field names to values for the entire column, usually just
name-> a valuedomaindomain matching this specific column
is_currentTrueif the current column should be specifically outlined in the grid,Falseotherwiseformathow to format the values of that column/type from
read_groupformatting toread_gridformatting (matchingvaluesin ColumnInfo)
ACL¶
if the view is not editable, individual cells wonât be editable
if the view is not creatable, the
Add a Linebutton will not be displayed (it currently creates a new empty record)
Context Keys¶
grid_rangeselects which range should be used by default if the view has multiple ranges
grid_anchorif applicable, used as the default anchor of column ranges instead of whatever
read_griddefines as its default.For date fields, the reference date around which the initial span will be computed. The default date anchor is âtodayâ (in the userâs timezone)
Kanban¶
The kanban view is a kanban board visualisation: it displays records as âcardsâ, halfway between a list view and a non-editable form view. Records may be grouped in columns for use in workflow visualisation or manipulation (e.g. tasks or work-progress management), or ungrouped (used simply to visualize records).
Note
The kanban view will load and display a maximum of ten columns. Any column after that will be closed (but can still be opened by the user).
The root element of the Kanban view is <kanban>, it can use the following
attributes:
default_group_bywhether the kanban view should be grouped if no grouping is specified via the action or the current search. Should be the name of the field to group by when no grouping is otherwise specified
default_ordercards sorting order used if the user has not already sorted the records (via the list view)
classadds HTML classes to the root HTML element of the Kanban view
examplesif set to a key in the KanbanExamplesRegistry, examples on column setups will be available in the grouped kanban view. Here is an example of how to define those setups.
group_createwhether the âAdd a new columnâ bar is visible or not. Default: true.
group_deletewhether groups can be deleted via the context menu. Default: true.
group_editwhether groups can be edited via the context menu. Default: true.
archivablewhether records belonging to a column can be archived / restored if an
activefield is defined on the model. Default: true.quick_createwhether it should be possible to create records without switching to the form view. By default,
quick_createis enabled when the Kanban view is grouped by many2one, selection, char or boolean fields, and disabled when not.quick_create_viewformview reference, specifying the view used for records quick creation.records_draggablewhether it should be possible to drag records when kanban is grouped. Default: true.
Set to
trueto always enable it, and tofalseto always disable it.groups_draggablewhether it should be possible to resequence colunms when kanban is grouped. Default: true.
Set to
trueto always enable it, and tofalseto always disable it.
Possible children of the view element are:
fielddeclares fields to use in kanban logic. If the field is simply displayed in the kanban view, it does not need to be pre-declared.
Possible attributes are:
name(required)the name of the field to fetch
headerdefines custom buttons similar to list view buttons in the control panel that perform an action/call a modelâs method.
<header> <button name="toDoAlways" type="object" string="Always displayed" display="always"/> <button name="toDoSelection" type="object" string="Displayed if selection"/> </header>
Does not support any attribute but can have children:
buttonas a list view button which accepts an extra attribute when placed in a
header:displayBy default, those buttons are only displayed when some records are selected, and they apply on the selection. When the attribute
displayis set toalways, the button is available all the time, even if thereâs no selection.
Note
Currently, only the always option is usable because it is not yet possible
to select records in a kanban view. This should happen soon.
progressbardeclares a progressbar element to put on top of kanban columns.
Possible attributes are:
field(required)the name of the field whose values are used to subgroup columnâs records in the progressbar
colors(required)JSON mapping the above field values to either âdangerâ, âwarningâ, âsuccessâ or âmutedâ colors
sum_field(optional)the name of the field whose columnâs recordsâ values will be summed and displayed next to the progressbar (if omitted, displays the total number of records)
templatesdefines a list of QWeb Templates templates. Cards definition may be split into multiple templates for clarity, but kanban views must define at least one root template
kanban-box, which will be rendered once for each record.Two additional templates can be defined:
kanban-menuandkanban-tooltip. If defined, thekanban-menutemplate is rendered inside a dropdown that can be toggled with a vertical ellipsis (âź) on the top right of the card. Thekanban-tooltiptemplate is rendered inside a tooltip when hovering kanban cards.The kanban view uses mostly-standard javascript qweb and provides the following context variables:
widgetthe current
KanbanRecord(), can be used to fetch some meta-information. These methods are also available directly in the template context and donât need to be accessed viawidgetrecordan object with all the requested fields as its attributes. Each field has two attributes
valueandraw_value, the former is formatted according to current user parameters, the latter is the direct value from aread()(except for date and datetime fields that are formatted according to userâs locale)contextthe current context, coming from the action, and the one2many or many2many field in the case of a Kanban view embedded in a Form view
user_contextself-explanatory
read_only_modeself-explanatory
selection_modeset to true when kanban view is opened in mobile environment from m2o/m2m field for selecting records.
Note
clicking on m2o/m2m field in mobile environment opens kanban view
buttons and fields
While most of the Kanban templates are standard QWeb Templates, the Kanban view processes
field,buttonandaelements specially:by default fields are replaced by their formatted value, unless the
widgetattribute is specified, in which case their rendering and behavior depends on the corresponding widget. Possible values are (among others):handlefor
sequence(orinteger) fields by which records are sorted, allows to drag&drop records to reorder them.
buttons and links with a
typeattribute become perform Odoo-related operations rather than their standard HTML function. Possible types are:action,objectstandard behavior for Odoo buttons, most attributes relevant to standard Odoo buttons can be used.
openopens the cardâs record in the form view in read-only mode
editopens the cardâs record in the form view in editable mode
deletedeletes the cardâs record and removes the card
If you need to extend the Kanban view, see KanbanRecord().
List¶
The root element of list views is <tree>2. The list viewâs
root can have the following attributes:
editableby default, selecting a list viewâs row opens the corresponding form view. The
editableattributes makes the list view itself editable in-place.Valid values are
topandbottom, making new records appear respectively at the top or bottom of the list.The architecture for the inline form view is derived from the list view. Most attributes valid on a form viewâs fields and buttons are thus accepted by list views although they may not have any meaning if the list view is non-editable
Note
if the
editattribute is set tofalse, theeditableoption will be ignored.multi_editeditable or not editable list can activate the multi-editing feature by defining the
multi_edit=1default_group_bywhether the list view should be grouped if no grouping is specified via the action or the current search. Should be the name of the field to group by when no grouping is otherwise specified
default_orderoverrides the ordering of the view, replacing the modelâs order (
_ordermodel attribute). The value is a comma-separated list of fields, postfixed bydescto sort in reverse order:<tree default_order="sequence,name desc"> ... </tree>
decoration-{$name}allow changing the style of a rowâs text based on the corresponding recordâs attributes.
{$name}can bebf(font-weight: bold),it(font-style: italic), or any bootstrap contextual color (danger,info,muted,primary,successorwarning).create,edit,delete,import,export_xlsxallows disabling the corresponding action in the view by setting the corresponding attribute to
falselimitthe default size of a page. It must be a positive integer
groups_limitwhen the list view is grouped, the default number of groups of a page. It must be a position integer
expandwhen the list view is grouped, automatically open the first level of groups if set to true (default: false)
Possible children elements of the list view are:
buttondisplays a button in a list cell
iconicon to use to display the button
stringif there is no
icon, the buttonâs textif there is an
icon,alttext for the icon
typetype of button, indicates how it clicking it affects Odoo:
objectcall a method on the listâs model. The buttonâs
nameis the method, which is called with the current rowâs record id and the current context.actionload an execute an
ir.actions, the buttonâsnameis the database id of the action. The context is expanded with the listâs model (asactive_model), the current rowâs record (active_id) and all the records currently loaded in the list (active_ids, may be just a subset of the database records matching the current search)
namesee
typegroupslists the groups which should be able to see the button
argssee
typeattrsdynamic attributes based on record values.
A mapping of attributes to domains, domains are evaluated in the context of the current rowâs record, if
Truethe corresponding attribute is set on the cell.Possible attribute is
invisible(hides the button).statesshorthand for
invisibleattrs: a list of states, comma separated, requires that the model has astatefield and that it is used in the view.Makes the button
invisibleif the record is not in one of the listed statesDanger
Using
statesin combination withattrsmay lead to unexpected results as domains are combined with a logical AND.contextmerged into the viewâs context when performing the buttonâs Odoo call
fielddefines a column where the corresponding field should be displayed for each record. Can use the following attributes:
namethe name of the field to display in the current model. A given name can only be used once per view
stringthe title of the fieldâs column (by default, uses the
stringof the modelâs field)invisiblefetches and stores the field, but doesnât display the column in the table. Necessary for fields which shouldnât be displayed but are used by e.g.
@colorsgroupslists the groups which should be able to see the field
widgetalternate representations for a fieldâs display. Possible list view values are (among others):
progressbardisplays
floatfields as a progress bar.handlefor
sequence(orinteger) fields by which records are sorted, instead of displaying the fieldâs value just displays a drag&drop icon to reorder records.
sum,avgdisplays the corresponding aggregate at the bottom of the column. The aggregation is only computed on currently displayed records. The aggregation operation must match the corresponding fieldâs
group_operatorattrsdynamic attributes based on record values. Only effects the current field, so e.g.
invisiblewill hide the field but leave the same field of other records visible, it will not hide the column itselfwidth(foreditable)when there is no data in the list, the width of a column can be forced by setting this attribute. The value can be an absolute width (e.g. â100pxâ). Note that when there are records in the list, we let the browser automatically adapt the columnâs widths according to their content, and this attribute is thus ignored.
decoration-{$name}allow changing the style of a cellâs text based on the corresponding recordâs attributes.
{$name}can bebf(font-weight: bold),it(font-style: italic), or any bootstrap contextual color (danger,info,muted,primary,successorwarning).nolabelif set to â1â, the column header will remain empty. Also, the column wonât be sortable.
optionalmakes the column optional. If set to âhideâ, the column is hidden by default. If set to âshowâ, the column is visible by default. User visibility choices are stored in the browser local storage.
Note
if the list view is
editable, any field attribute from the form view is also valid and will be used when setting up the inline form view.Note
In case of list sub-views (One2many/Many2many display in a form view), The attribute
column_invisiblecan be useful to hide a column depending on the parent object.<field name="product_is_late" attrs="{'column_invisible': [('parent.has_late_products', '=', False)]}"/>
Note
When a list view is grouped, numeric fields are aggregated and displayed for each group. Also, if there are too many records in a group, a pager will appear on the right of the group row. For this reason, it is not a good practice to have a numeric field in the last column, when the list view is in a situation where it can be grouped (it is however fine for x2manys field in a form view: they cannot be grouped).
groupbydefines custom headers (with buttons) for the current view when grouping records on many2one fields. It is also possible to add
field, inside thegroupbywhich can be used for modifiers. These fields thus belong on the many2one comodel. These extra fields will be fetched in batch.namethe name of a many2one field (on the current model). Custom header will be displayed when grouping the view on this field name.
<groupby name="partner_id"> <field name="name"/> <!-- name of partner_id --> <button type="edit" name="edit" string="Edit"/> <button type="object" name="my_method" string="Button1" attrs="{'invisible': [('name', '=', 'Georges')]}"/> </groupby>
A special button (
type="edit") can be defined to open the many2one form view.
headerdefines custom buttons similar to list view buttons in the control panel that perform an action/call a modelâs method.
<header> <button name="toDoAlways" type="object" string="Always displayed" display="always"/> <button name="toDoSelection" type="object" string="Displayed if selection"/> </header>
Does not support any attribute but can have children:
buttonas a list view button which accepts an extra attribute when placed in a
header:displayBy default, those buttons are only displayed when some records are selected, and they apply on the selection. When the attribute
displayis set toalways, the button is available all the time, even if thereâs no selection.
controldefines custom controls for the current view.
This makes sense if the parent
treeview is inside a One2many field.Does not support any attribute, but can have children:
createadds a button to create a new element on the current list.
Note
If any
createis defined, it will overwrite the default âadd a lineâ button.The following attributes are supported:
string(required)The text displayed on the button.
contextThis context will be merged into the existing context when retrieving the default value of the new record.
For example it can be used to override default values.
The following example will override the default âadd a lineâ button by replacing it with 3 new buttons: âAdd a productâ, âAdd a sectionâ and âAdd a noteâ.
âAdd a productâ will set the field âdisplay_typeâ to its default value.
The two other buttons will set the field âdisplay_typeâ to be respectively âline_sectionâ and âline_noteâ.
<control> <create string="Add a product" /> <create string="Add a section" context="{'default_display_type': 'line_section'}" /> <create string="Add a note" context="{'default_display_type': 'line_note'}" /> </control>
- 2
for historical reasons, it has its origin in tree-type views later repurposed to a more table/list-type display
Map¶
Enterprise featureThis view is able to display records on a map and the routes between them. The records are represented by pins. It also allows the visualization of fields from the model in a popup tied to the recordâs pin.
Note
The model on which the view is applied should contain a res.partner many2one since the view relies on the res.partnerâs address and coordinates fields to localize the records.
API¶
The view uses location data platformsâ API to fetch the tiles (the mapâs background), do the geoforwarding (converting addresses to a set of coordinates) and fetch the routes. The view implements two API, OpenStreetMap and MapBox. OpenStreetMap is used by default and is able to fetch tiles and do geoforwarding. This API does not require a token. As soon as a valid MapBox token is provided in the general settings the view switches to the MapBox API. This API is faster and allows the computation of routes. A token can be obtained by signing up to MapBox.
Structural components¶
The viewâs root element is <map>. It can have the following attributes:
res_partnerContains the
res.partnermany2one. If not provided the view resorts to create an empty map.default_orderIf a field is provided the view overrides the modelâs default order. The field must be part of the model on which the view is applied, not from
res.partner.routingif
1display the routes between the records. The view needs a valid MapBox token and at least two located records (i.e the records have ares.partnermany2one and the partner has an address or valid coordinates).hide_nameif
1hide the name from the pinâs popup (default:0).hide_addressif
1hide the address from the pinâs popup (default:0).hide_titleif
1hide the title from the pin list (default:0).panel_titleString to display as title of the pin list. If not provided, the title is the actionâs name or âItemsâ if the view is not in an action.
limitMaximum number of records to fetch (default: 80). It must be a positive integer.
The <map> element can contain multiple <field> elements. Each <field> element is interpreted as a line in the pinâs popup. The fieldâs attributes are the following:
nameThe field to display.
stringString to display before the fieldâs content. It can be used as a description.
- For example here is a map:
<map res_partner="partner_id" default_order="date_begin" routing="1" hide_name="1"> <field name="partner_id" string="Customer Name"/> </map>
Pivot¶
The pivot view is used to visualize aggregations as a pivot table. Its root
element is <pivot> which can take the following attributes:
disable_linking(optional)Set to
1to remove table cellâs links to list view.display_quantity(optional)Set to
1to display the Quantity column by default.default_order(optional)The name of the measure and the order (asc or desc) to use as default order in the view.
<pivot default_order="foo asc"> <field name="foo" type="measure"/> </pivot>
The only allowed element within a pivot view is field which can have the
following attributes:
name(mandatory)the name of a field to use in the view. If used for grouping (rather than aggregating)
string(optional)the name that will be used to display the field in the pivot view, overrides the default python String attribute of the field.
type(optional)indicates whether the field should be used as a grouping criteria or as an aggregated value within a group. Possible values are:
row(default)groups by the specified field, each group gets its own row.
colcreates column-wise groups
measurefield to aggregate within a group
intervalon date and datetime fields, groups by the specified interval (
day,week,month,quarteroryear) instead of grouping on the specific datetime (fixed second resolution) or date (fixed day resolution).
invisible(optional)if true, the field will not appear either in the active measures nor in the selectable measures (useful for fields that do not make sense aggregated, such as fields in different units, e.g. ⏠and $).
The measures are automatically generated from the model fields; only the aggregatable fields are used. Those measures are also alphabetically sorted on the string of the field.
Warning
like the graph view, the pivot aggregates data on database content which means that non-stored function fields can not be used in pivot views
In Pivot view a field can have a widget attribute to dictate its format.
The widget should be a field formatter, of which the most interesting are
date, datetime, float_time, and monetary.
For instance a timesheet pivot view could be defined as:
<pivot string="Timesheet">
<field name="employee_id" type="row"/>
<field name="date" interval="month" type="col"/>
<field name="unit_amount" type="measure" widget="float_time"/>
</pivot>
QWeb¶
QWeb views are standard QWeb Templates templates inside a viewâs
arch. They donât have a specific root element. Because QWeb views donât
have a specific root element, their type must be specified explicitly (it can
not be inferred from the root element of the arch field).
QWeb views have two use cases:
they can be used as frontend templates, in which case template should be used as a shortcut.
they can be used as actual qweb views (opened inside an action), in which case they should be defined as regular view with an explicit
type(it can not be inferred) and a model.
The main additions of qweb-as-view to the basic qweb-as-template are:
qweb-as-view has a special case for a
<nav>element bearing the CSS classo_qweb_cp_buttons: its contents should be buttons and will be extracted and moved to the control panelâs button area, the<nav>itself will be removed, this is a work-around to control panel views not existing yetqweb-as-view rendering adds several items to the standard qweb rendering context:
modelthe model to which the qweb view is bound
domainthe domain provided by the search view
contextthe context provided by the search view
recordsa lazy proxy to
model.search(domain), this can be used if you just want to iterate the records and not perform more complex operations (e.g. grouping)
qweb-as-view also provides additional rendering hooks:
_qweb_prepare_context(view_id, domain)prepares the rendering context specific to qweb-as-viewqweb_render_view(view_id, domain)is the method called by the client and will call the context-preparation methods and ultimatelyenv['ir.qweb'].render().
Search¶
Search views are a break from previous view types in that they donât display content: although they apply to a specific model, they are used to filter other viewâs content (generally aggregated views e.g. List or Graph). Beyond that difference in use case, they are defined the same way.
The root element of search views is <search>. It takes no attributes.
Possible children elements of the search view are:
fieldfields define domains or contexts with user-provided values. When search domains are generated, field domains are composed with one another and with filters using AND.
Fields can have the following attributes:
namethe name of the field to filter on
stringthe fieldâs label
operatorby default, fields generate domains of the form
[(name, operator, provided_value)]wherenameis the fieldâs name andprovided_valueis the value provided by the user, possibly filtered or transformed (e.g. a user is expected to provide the label of a selection fieldâs value, not the value itself).The
operatorattribute allows overriding the default operator, which depends on the fieldâs type (e.g.=for float fields butilikefor char fields)filter_domaincomplete domain to use as the fieldâs search domain, can use a
selfvariable to inject the provided value in the custom domain. Can be used to generate significantly more flexible domains thanoperatoralone (e.g. searches on multiple fields at once)If both
operatorandfilter_domainare provided,filter_domaintakes precedence.contextallows adding context keys, including the user-provided values (which as for
domainare available as aselfvariable, an array of values e.g.[id_1, id_2]for aMany2onefield). By default, fields donât generate domains.Note
the domain and context are inclusive and both are generated if a
contextis specified. To only generate context values, setfilter_domainto an empty list:filter_domain="[]"groupsmake the field only available to specific users
domainif the field can provide an auto-completion (e.g.
Many2one), filters the possible completion results.
filtera filter is a predefined toggle in the search view, it can only be enabled or disabled. Its main purposes are to add data to the search context (the context passed to the data view for searching/filtering), or to append new sections to the search filter.
Filters can have the following attributes:
string(required)the label of the filter
domain(optional)an Odoo domain, will be appended to the actionâs domain as part of the search domain.
date(optional)the name of a field of type
dateordatetime. Using this attribute has the effect to create a set of filters available in a submenu of the filters menu. The filters proposed are time dependent but not dynamic in the sense that their domains are evaluated at the time of the control panel instantiation.Example:
<filter name="filter_create_date" date="create_date" string="Creation Date"/>
The example above allows to easily search for records with creation date field values in one of the periods below (if the current month is August 2019).
Create Date > August July June Q4 Q3 Q2 Q1 -------------- 2019 2018 2017
Multi selection of options is allowed.
default_period(optional)only makes sense for a filter with non empty
dateattribute. determines which periods are activated if the filter is in the default set of filters activated at the view initialization. If not provided, âthis_monthâ is used by default.To choose among the following options: today, this_week, this_month, last_month, antepenultimate_month, fourth_quarter, third_quarter, second_quarter, first_quarter, this_year, last_year, antepenultimate_year.
The attribute accepts comma separated values.
Examples:
<filter name="filter_create_date" date="create_date" string="Creation Date" default_period="this_week"/> <filter name="filter_create_date" date="create_date" string="Creation Date" default_period="this_year,last_year"/>
contexta Python dictionary, merged into the actionâs domain to generate the search domain
The key
group_bycan be used to define a groupby available in the âGroup Byâ menu. The âgroup_byâ value can be a valid field name.<filter name="groupby_category" string="Category" context="{'group_by': 'category_id'}"/>
The groupby defined above allows to group data by category.
When the field is of type
dateordatetime, the filter generates a submenu of the Group By menu in which the following interval options are available: day, week, month, quarter, year.In case the filter is in the default set of filters activated at the view initialization, the records are grouped by month by default. This can be changed by using the syntax âdate_field:intervalâ as in the following example.
Example:
<filter name="groupby_create_date" string="Creation Date" context="{'group_by': 'create_date:week'}"/>
Note
The results of read_groups grouped on a field may be influenced by its group_expand attribute, allowing to display empty groups when needed. For more information, please refer to
Fieldattributes documentation.namelogical name for the filter, can be used to enable it by default, can also be used as inheritance hook
helpa longer explanatory text for the filter, may be displayed as a tooltip
groupsmakes a filter only available to specific users
Tip
New in version 7.0.
Sequences of filters (without non-filters separating them) are treated as inclusively composited: they will be composed with
ORrather than the usualAND, e.g.<filter domain="[('state', '=', 'draft')]"/> <filter domain="[('state', '=', 'done')]"/>
if both filters are selected, will select the records whose
stateisdraftordone, but<filter domain="[('state', '=', 'draft')]"/> <separator/> <filter domain="[('delay', '<', 15)]"/>
if both filters are selected, will select the records whose
stateisdraftanddelayis below 15.Note
XML does not allow
<to be used within XML elements, an entity reference (<) should be used instead.separatorcan be used to separates groups of filters in simple search views
groupcan be used to separate groups of filters, more readable than
separatorin complex search viewssearchpanelallows to display a search panel on the left of any multi records view. By default, the list and kanban views have the searchpanel enabled. The search panel can be activated on other views with the attribute:
view_typesa comma separated list of view types on which to enable the search panel default: âtree,kanbanâ
This tool allows to quickly filter data on the basis of given fields. The fields are specified as direct children of the
searchpanelwith tag namefield, and the following attributes:name(mandatory)the name of the field to filter on
selectdetermines the behavior and display. Possible values are
one(default) at most one value can be selected. Supported field types are many2one and selection.multiseveral values can be selected (checkboxes). Supported field types are many2one, many2many and selection.
groupsrestricts to specific users
stringdetermines the label to display
iconspecifies which icon is used
colordetermines the icon color
Additional optional attributes are available in the
multicase:enable_countersdefault is false. If set to true the record counters will be computed and displayed if non-zero.
This feature has been implemented in case performances would be too bad.
Another way to solve performance issues is to properly override the
search_panel_select_rangeandsearch_panel_select_multi_rangemethods.expanddefault is false. If set to false categories or filters with 0 records will be hidden.
limitdefault is 200. Integer determining the maximal number of values to fetch for the field. If the limit is reached, no values will be displayed in the search panel and an error message will appear instead because we consider that is useless / bad performance-wise. All values will be fetched if set to 0.
Additional optional attributes are available according to the chosen case:
For the
onecase:hierarchize(only available for many2one fields) default is true. Handles the display style of categories :
If set to true child categories will appear under their related parent. If not, all categories will be displayed on the same level.
For the
multicase:domain:determines conditions that the comodel records have to satisfy.
A domain might be used to express a dependency on another field (with select=âoneâ) of the search panel. Consider /!This attribute is incompatible with a select=âoneâ with enabled counters; if a select=âmultiâ has a
domainattribute, all select=âoneâ will have their counters disabled.<searchpanel> <field name="department_id"/> <field name="manager_id" select="multi" domain="[('department_id', '=', department_id)]"/> </searchpanel>
In the above example, the range of values for manager_id (manager names) available at screen will depend on the value currently selected for the field
department_id.groupby: field name of the comodel (only available for many2one and many2many fields). Values will be grouped by that field.
Search defaults¶
Search fields and filters can be configured through the actionâs context
using search_default_name keys. For fields, the value should be the
value to set in the field, for filters itâs a boolean value or a number. For instance,
assuming foo is a field and bar is a filter an action context of:
{
'search_default_foo': 'acro',
'search_default_bar': 1
}
will automatically enable the bar filter and search the foo field for
acro.
A numeric value (between 1 and 99) can be used to describe the order of default groupbys.
For instance if foo and bar refer to two groupbys
{
'search_default_foo': 2,
'search_default_bar': 1
}
has the effect to activate first bar then foo.