### Clone Odoo Petstore Module
Source: https://www.odoo.com/documentation/12.0/developer/howtos/web
This command downloads the example Odoo module ('petstore') from GitHub. This module serves as a starting point for customizing the web client and testing the web framework.
```bash
$ git clone http://github.com/odoo/petstore
```
--------------------------------
### Start Odoo Server
Source: https://www.odoo.com/documentation/12.0/developer/howtos/backend
Command to start the Odoo server. Ensure the full path to 'odoo-bin' is provided if it's not in your system's PATH. The server runs using a client/server architecture.
```bash
odoo-bin
```
--------------------------------
### Basic Counter Widget Example
Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference
An example demonstrating how to create a basic counter widget, including its template, initialization, event handling, and rendering.
```APIDOC
## Basic Counter Widget Example
### Description
This example shows a simple counter widget with an increment button. It utilizes Odoo's event system and QWeb templating.
### Widget Definition
```javascript
var Widget = require('web.Widget');
var Counter = Widget.extend({
template: 'some.template',
events: {
'click button': '_onClick',
},
init: function (parent, value) {
this._super(parent);
this.count = value;
},
_onClick: function () {
this.count++;
this.$('.val').text(this.count);
},
});
```
### Template (`some.template`)
```html
```
### Usage
```javascript
// Create the instance
var counter = new Counter(this, 4);
// Render and insert into DOM
counter.appendTo(".some-div");
```
```
--------------------------------
### Build and install pyflame
Source: https://www.odoo.com/documentation/12.0/developer/howtos/profilecode
This sequence of commands downloads the `pyflame` source code, configures the build environment, compiles the profiler, and installs it system-wide. It requires running `autogen.sh`, `configure`, and `make` before a final `sudo make install`.
```bash
git clone https://github.com/uber/pyflame.git
git clone https://github.com/brendangregg/FlameGraph.git
cd pyflame
./autogen.sh
./configure
make
sudo make install
```
--------------------------------
### Start Odoo Server with Custom Addons Path
Source: https://www.odoo.com/documentation/12.0/developer/howtos/website
This command starts the Odoo server, specifying additional directories where Odoo should look for modules. This is useful for loading newly developed or custom modules.
```bash
$ ./odoo-bin --addons-path addons,my-modules
```
--------------------------------
### Superlaser Endpoint Example
Source: https://www.odoo.com/documentation/12.0/developer/webservices/iap
An example of how the authorize, cancel, and capture functions might be used within a JSON-RPC endpoint.
```APIDOC
## Superlaser Endpoint Example
### Description
An example of how the authorize, cancel, and capture functions might be used within a JSON-RPC endpoint.
### Method
`POST`
### Endpoint
`/deathstar/superlaser`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **user_account** (any) - Required - User account information.
- **coordinates** (any) - Required - Target coordinates.
- **target** (any) - Required - Target identifier.
- **factor** (float) - Optional - Superlaser power factor (0.0 to 1.0).
### Request Example
```json
{
"jsonrpc": "2.0",
"method": "call",
"params": {
"service": "deathstar.service",
"method": "superlaser",
"args": [
{
"user_account": "some_account_token",
"coordinates": {"x": 10, "y": 20},
"target": "Alderaan",
"factor": 0.8
}
]
}
}
```
### Response
#### Success Response (200)
- **result** (any) - The result of the superlaser operation.
#### Response Example
```json
{
"jsonrpc": "2.0",
"id": null,
"result": "Superlaser fired successfully!"
}
```
### Error Handling
- If an exception occurs during the process, the `cancel` function may be called, and the exception is re-raised.
```
--------------------------------
### Odoo Account Template Example
Source: https://www.odoo.com/documentation/12.0/developer/webservices/localization
An example of creating a specific account template record for 'Clients' in Odoo. It shows how to set the name, code, user type, and chart template ID.
```xml
Clients4000
```
--------------------------------
### Odoo TransactionCase Model Testing Example (Python)
Source: https://www.odoo.com/documentation/12.0/developer/reference/testing
Demonstrates how to test a model's properties and actions using `odoo.tests.common.TransactionCase`. Test methods must start with `test_`. This example creates a record, performs an action, and asserts the expected field value.
```python
from odoo.tests import common
class TestModelA(common.TransactionCase):
def test_some_action(self):
record = self.env['model.a'].create({'field': 'value'})
record.some_action()
self.assertEqual(
record.field,
expected_field_value)
# other tests...
```
--------------------------------
### Widget Lifecycle Methods
Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference
Details on the various stages of a widget's lifecycle, including `init`, `willStart`, rendering, `start`, and `destroy`.
```APIDOC
## Widget Lifecycle
### Description
The widget class follows a defined lifecycle: `init`, `willStart`, rendering, `start`, and `destroy`.
### `Widget.init(parent)`
- **Description**: The constructor for the widget. Initializes the base state.
- **Arguments**:
- `parent` (`Widget()`): The parent widget, used for destruction and event propagation. Can be `null`.
### `Widget.willStart()`
- **Description**: Called when a widget is created and about to be appended to the DOM. Should return a deferred.
- **Purpose**: Useful for performing asynchronous operations before rendering.
### `[Rendering]`
- **Description**: An automatic framework process. Renders the widget's template (if defined) or creates a DOM element based on `tagName`. Binds events defined in `events` and `custom_events`.
- **Output**: Sets the widget's `$el` property.
### `Widget.start()`
- **Description**: Called after rendering is complete. Useful for post-rendering tasks like library setup.
- **Returns**: A deferred object indicating completion.
### `Widget.destroy()`
- **Description**: The final step in a widget's life. Performs cleanup operations like unbinding events and removing the widget from the component tree.
- **Note**: Automatically called when the parent is destroyed. Must be called explicitly if the widget has no parent or is removed independently.
```
--------------------------------
### Example: VAT Leasing Tax Configuration in Odoo XML (l10n_pl)
Source: https://www.odoo.com/documentation/12.0/developer/webservices/localization
This is a practical example of configuring a sales tax for vehicle leasing in Poland using Odoo's XML. It demonstrates how to set the tax name, description, amount, type, sequence, and link it to tax groups and tags. The `children_tax_ids` field shows how to group multiple tax components.
```xml
VAT - leasing pojazdu(sale)VLP1.00groupsale
```
--------------------------------
### Install build dependencies for pyflame on Debian/Ubuntu
Source: https://www.odoo.com/documentation/12.0/developer/howtos/profilecode
These commands install the necessary development tools and libraries required to compile `pyflame` on Debian-based systems. This includes build utilities like `make`, `g++`, and development headers for Python.
```bash
# These instructions are given for Debian/Ubuntu distributions
sudo apt install autoconf automake autotools-dev g++ pkg-config python-dev python3-dev libtool make
```
--------------------------------
### Python JSON-RPC Library for Odoo Interaction
Source: https://www.odoo.com/documentation/12.0/developer/howtos/backend
A Python 3 program demonstrating how to interact with an Odoo server using the JSON-RPC protocol. It utilizes standard Python libraries `urllib.request` and `json`. The example shows logging into the database and creating a new note. It assumes the 'note' app is installed.
```python
import json
import random
import urllib.request
HOST = 'localhost'
PORT = 8069
DB = 'openacademy'
USER = 'admin'
PASS = 'admin'
def json_rpc(url, method, params):
data = {
"jsonrpc": "2.0",
"method": method,
"params": params,
"id": random.randint(0, 1000000000),
}
req = urllib.request.Request(url=url, data=json.dumps(data).encode(), headers={
"Content-Type":"application/json",
})
reply = json.loads(urllib.request.urlopen(req).read().decode('UTF-8'))
if reply.get("error"):
raise Exception(reply["error"])
return reply["result"]
def call(url, service, method, *args):
return json_rpc(url, "call", {"service": service, "method": method, "args": args})
# log in the given database
url = "http://%s:%s/jsonrpc" % (HOST, PORT)
uid = call(url, "common", "login", DB, USER, PASS)
# create a new note
args = {
'color': 8,
'memo': 'This is another note',
'create_uid': uid,
}
note_id = call(url, "object", "execute", DB, uid, PASS, 'note.note', 'create', args)
```
--------------------------------
### Odoo XML: Belgian Chart of Accounts Example
Source: https://www.odoo.com/documentation/12.0/developer/webservices/localization
This XML snippet provides a concrete example of defining a Belgian Chart of Accounts template. It sets the name, currency to EUR, bank and cash account prefixes, and specifies Dutch as the spoken language.
```xml
Belgian PCMN550570
```
--------------------------------
### Client Action Example (ir.actions.client)
Source: https://www.odoo.com/documentation/12.0/developer/reference/actions
This snippet demonstrates how to trigger a client-side action using the 'ir.actions.client' type. It specifies the 'tag' to identify the client-side implementation, such as 'pos.ui' for the Point of Sale interface. Additional parameters can be passed via the 'params' dictionary.
```json
{
"type": "ir.actions.client",
"tag": "pos.ui"
}
```
--------------------------------
### Compose Widgets Using appendTo()
Source: https://www.odoo.com/documentation/12.0/developer/howtos/web
This example demonstrates widget composition, where one widget (`HomePage`) includes another (`GreetingsWidget`). The `GreetingsWidget` is instantiated and then appended to a part of the `HomePage`'s root element (`$el`) using the `appendTo()` method. The `start()` method of the child widget is called during `appendTo()`.
```javascript
local.HomePage = instance.Widget.extend({
start: function() {
this.$el.append("
Hello dear Odoo user!
");
var greeting = new local.GreetingsWidget(this);
return greeting.appendTo(this.$el);
},
});
```
--------------------------------
### Python Dictionary Creation and Update Idioms
Source: https://www.odoo.com/documentation/12.0/developer/reference/guidelines
Shows preferred Python idioms for creating and updating dictionaries, favoring conciseness and readability over older methods. It includes examples for empty dictionaries, initializing with values, and updating existing dictionaries.
```python
# -- creation empty dict
my_dict = {}
my_dict2 = dict()
# -- creation with values
# bad
# my_dict = {}
# my_dict['foo'] = 3
# my_dict['bar'] = 4
# good
my_dict = {'foo': 3, 'bar': 4}
# -- update dict
# bad
# my_dict['foo'] = 3
# my_dict['bar'] = 4
# my_dict['baz'] = 5
# good
my_dict.update(foo=3, bar=4, baz=5)
my_dict = dict(my_dict, **my_dict2)
```
--------------------------------
### Odoo Module Initialization File
Source: https://www.odoo.com/documentation/12.0/developer/howtos/backend
Example of an __init__.py file for an Odoo module. This file is essential for making the module a Python package and imports other Python files within the module.
```python
from . import mymodule
```
--------------------------------
### GET /academy//
Source: https://www.odoo.com/documentation/12.0/developer/howtos/website
A simple route that accepts a string parameter from the URL and displays it in an HTML heading. This demonstrates basic string extraction from the URL.
```APIDOC
## GET /academy//
### Description
This endpoint accepts a string name from the URL and returns it within an H1 HTML tag. It serves as a basic example of URL parameter handling.
### Method
GET
### Endpoint
/academy//
#### Path Parameters
- **name** (string) - Required - The name to be displayed in the heading.
### Request Example
(No request body for GET requests)
### Response
#### Success Response (200)
- **HTML String** - A string containing an H1 tag with the provided name.
#### Response Example
```html
Alice
```
```
--------------------------------
### Post-install Test Flag
Source: https://www.odoo.com/documentation/12.0/developer/reference/testing
Controls whether a test runs after module installations. Deprecated in favor of `tagged()`.
```APIDOC
## `odoo.tests.common.post_install`
### Description
Sets the post-install state of a test. The flag is a boolean specifying whether the test should or should not run after a set of module installations. By default, tests are not run after installation of all modules in the current installation set.
### Method
`post_install(flag)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```python
from odoo.tests import common
class TestMyModule(common.TransactionCase):
@common.post_install(True)
def test_post_install_feature(self):
# Test logic here
pass
```
### Response
#### Success Response (N/A)
This is a decorator, not an endpoint.
#### Response Example
N/A
```
--------------------------------
### Connecting to Odoo Demo Database
Source: https://www.odoo.com/documentation/12.0/developer/webservices/odoo
Examples in Python, Ruby, PHP, and Java to connect to the Odoo demo server and retrieve connection details.
```APIDOC
## Connecting to Odoo Demo Database
### Description
This section provides examples for connecting to the Odoo demo server (`https://demo.odoo.com/start`) to obtain connection parameters such as host, database name, username, and password.
### Method
XML-RPC calls to the `/start` endpoint.
### Endpoints
- `https://demo.odoo.com/start`
### Parameters
None directly for the `/start` endpoint, but the response contains:
- **host** (string) - The server host address.
- **database** (string) - The name of the demo database.
- **user** (string) - The username for accessing the database.
- **password** (string) - The password for authentication.
### Request Example
```python
import xmlrpc.client
info = xmlrpc.client.ServerProxy('https://demo.odoo.com/start').start()
url, db, username, password = \
info['host'], info['database'], info['user'], info['password']
```
### Response
Returns a dictionary containing connection details.
### Response Example
```json
{
"host": "some.host.com",
"database": "demo_db_name",
"user": "demo_user",
"password": "demo_password"
}
```
```
--------------------------------
### Odoo Javascript Module Definition Example
Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference
Demonstrates how to define Javascript modules in Odoo using the 'odoo.define' function. This includes basic module definition and module definition with explicit dependencies, showing how to import and use other modules.
```javascript
odoo.define('module.A', function (require) {
"use strict";
var A = ...;
return A;
});
odoo.define('module.B', function (require) {
"use strict";
var A = require('module.A');
var B = ...; // something that involves A
return B;
});
```
```javascript
odoo.define('module.Something', ['module.A', 'module.B'], function (require) {
"use strict";
var A = require('module.A');
var B = require('module.B');
// some code
});
```
--------------------------------
### RPC Call to Directly Access a Controller in JavaScript
Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference
This JavaScript example illustrates how to make an RPC call to directly access a controller on a specific route. It utilizes the `_rpc` helper, providing the route and any necessary parameters for the controller.
```javascript
return this._rpc({
route: '/some/route/',
params: { some: kwargs},
});
```
--------------------------------
### Running Odoo Tests from a Specific Module
Source: https://www.odoo.com/documentation/12.0/developer/reference/testing
This command-line example shows how to run tests exclusively from a particular Odoo module, such as 'sale', using the `odoo-bin` command with `--test-enable` and `--test-tags`. This is useful for isolating tests during development or debugging.
```bash
odoo-bin --test-enable --test-tags sale
```
--------------------------------
### Get Widget Children
Source: https://www.odoo.com/documentation/12.0/developer/howtos/web
Illustrates how to obtain a list of all direct child widgets of the current widget using the `getChildren()` method. The example accesses the root element of the first child widget in the returned array.
```javascript
local.HomePage = instance.Widget.extend({
start: function() {
var greeting = new local.GreetingsWidget(this);
greeting.appendTo(this.$el);
console.log(this.getChildren()[0].$el);
// will print "div.oe_petstore_greetings" in the console
},
});
```
--------------------------------
### Iterating Through a Recordset in Odoo
Source: https://www.odoo.com/documentation/12.0/developer/reference/orm
Illustrates how to iterate over an Odoo recordset. Each iteration yields a singleton recordset (containing a single record). This is analogous to iterating over a string to get individual characters. The example shows printing the recordset and individual records.
```python
def do_operation(self):
print self # => a.model(1, 2, 3, 4, 5)
for record in self:
print record # => a.model(1), then a.model(2), then a.model(3), ...
```
--------------------------------
### Create Demo Course Products (XML)
Source: https://www.odoo.com/documentation/12.0/developer/howtos/website
XML records defining sample course products. Each record uses 'product.template' and links to the 'academy.category_courses' category. It sets the course as published on the website, defines a list price, and specifies the product type as 'service'.
```xml
Course 0True0serviceCourse 1True0serviceCourse 2True0service
```
--------------------------------
### Get Start/End of Period in Odoo
Source: https://www.odoo.com/documentation/12.0/developer/reference/orm
These static methods, available on both `fields.Date` and `fields.Datetime`, allow you to easily calculate the start or end of a specified time period (year, quarter, month, week, day, hour) from a given date or datetime value.
```python
# Get the start of the month for a given date
start_of_month = fields.Date.start_of(some_date, 'month')
# Get the end of the day for a given datetime
end_of_day = fields.Datetime.end_of(some_datetime, 'day')
```
--------------------------------
### Odoo SingleTransactionCase for Shared Test Transaction
Source: https://www.odoo.com/documentation/12.0/developer/reference/testing
Shows how to use `odoo.tests.common.SingleTransactionCase` where all test methods within a class execute within a single database transaction. The transaction starts with the first test and is rolled back only after the last test method completes. This is useful for tests that benefit from shared setup within a transaction.
```python
import odoo.tests
class TestSharedTransaction(odoo.tests.common.SingleTransactionCase):
def test_first_method(self):
# Logic that affects subsequent tests in the same transaction
pass
def test_second_method(self):
# This method runs after test_first_method within the same transaction
pass
```
--------------------------------
### Running Odoo Tests with Specific Tags via Command Line
Source: https://www.odoo.com/documentation/12.0/developer/reference/testing
These command-line examples illustrate how to execute Odoo tests using the `odoo-bin` command with the `--test-enable` and `--test-tags` options. It shows how to run tests tagged with 'nice', combined tags like 'nice,standard', and how to exclude tests using a minus prefix like 'standard,-slow'.
```bash
odoo-bin --test-enable --test-tags nice
```
```bash
odoo-bin --test-enable --test-tags nice,standard
```
```bash
odoo-bin --test-enable --test-tags 'standard,-slow'
```
--------------------------------
### Odoo XML Naming Conventions for Views, Actions, Menus, and Security
Source: https://www.odoo.com/documentation/12.0/developer/reference/guidelines
Provides examples of naming conventions for various Odoo components including menus, views, actions, and security groups/rules. These conventions aid in maintaining consistency and organization within Odoo modules. No external dependencies are required.
```xml
model.name.view.form
...
model.name.view.kanban
...
Model Main Action
...
Model Access Children
...
...
...
```
--------------------------------
### Odoo Inheritance Usage Example
Source: https://www.odoo.com/documentation/12.0/developer/reference/orm
Shows how to create and use models defined with classical inheritance in Odoo. This example demonstrates creating records of both the base and inherited models and calling their methods.
```python
# Assuming Inheritance0 and Inheritance1 are defined as above
a = env['inheritance.0'].create({'name': 'A'})
b = env['inheritance.1'].create({'name': 'B'})
result_a = a.call()
result_b = b.call()
# result_a will be "This is model 0 record A"
# result_b will be "This is model 1 record B"
```
--------------------------------
### Odoo Classical Inheritance Example
Source: https://www.odoo.com/documentation/12.0/developer/reference/orm
Demonstrates classical inheritance in Odoo, where a new model inherits fields and methods from a base model using _inherit. This example shows overriding a method.
```python
class Inheritance0(models.Model):
_name = 'inheritance.0'
_description = 'Inheritance Zero'
name = fields.Char()
def call(self):
return self.check("model 0")
def check(self, s):
return "This is {} record {}".format(s, self.name)
class Inheritance1(models.Model):
_name = 'inheritance.1'
_inherit = 'inheritance.0'
_description = 'Inheritance One'
def call(self):
return self.check("model 1")
```
--------------------------------
### Python Function Return and Builtin Usage
Source: https://www.odoo.com/documentation/12.0/developer/reference/guidelines
Explains Python best practices for function returns and utilizing built-in functions for conciseness. It shows how to simplify multiple return points and effectively use `dict.get()` instead of redundant checks.
```python
# Multiple return points are OK, when they’re simpler
# a bit complex and with a redundant temp variable
# def axes(self, axis):
# axes = []
# if type(axis) == type([]):
# axes.extend(axis)
# else:
# axes.append(axis)
# return axes
# clearer
def axes(self, axis):
if type(axis) == type([]):
return list(axis) # clone the axis
else:
return [axis] # single-element list
# Know your builtins
# value = my_dict.get('key', None) # very very redundant
value = my_dict.get('key') # good
```
--------------------------------
### Running Odoo Tests from a Module or with a Specific Tag
Source: https://www.odoo.com/documentation/12.0/developer/reference/testing
This command-line example shows how to run tests from either the 'stock' module or any test tagged as 'slow'. It uses the `odoo-bin` command with `--test-enable` and `--test-tags`, illustrating additive tag selection.
```bash
odoo-bin --test-enable --test-tags '-standard, slow, stock'
```
--------------------------------
### Timesheet Pivot View Example
Source: https://www.odoo.com/documentation/12.0/developer/reference/views
A comprehensive example of an Odoo pivot view for timesheet data. It includes grouping by employee and date (monthly interval), and aggregating unit amount with a float time widget.
```xml
```
--------------------------------
### Create a Basic Odoo Controller
Source: https://www.odoo.com/documentation/12.0/developer/howtos/website
This Python code defines a simple Odoo controller that handles web requests. It imports the necessary Odoo components and defines a route that returns a 'Hello, world' string.
```python
# -*- coding: utf-8 -*-
from odoo import http
class Academy(http.Controller):
@http.route('/academy/academy/', auth='public')
def index(self, **kw):
return "Hello, world"
```
--------------------------------
### Odoo Filter Example
Source: https://www.odoo.com/documentation/12.0/developer/reference/views
An example of an Odoo filter definition within an XML view. The 'name' attribute is a logical identifier, 'string' provides a display label, and 'context' specifies grouping behavior, here by the week of the creation date.
```xml
```
--------------------------------
### Python Iteration and Dictionary `setdefault` Usage
Source: https://www.odoo.com/documentation/12.0/developer/reference/guidelines
Advises on efficient Python iteration techniques, favoring direct dictionary iteration over `.keys()` and showing the utility of `dict.setdefault()` for simplifying the creation of default dictionary values.
```python
# Iterate on iterables
# creates a temporary list and looks bar
# for key in my_dict.keys():
# "do something..."
# better
for key in my_dict:
"do something..."
# accessing the key,value pair
for key, value in my_dict.items():
"do something..."
# Use dict.setdefault
# longer.. harder to read
# values = {}
# for element in iterable:
# if element not in values:
# values[element] = []
# values[element].append(other_value)
# Use setdefault for cleaner code
values = {}
for element in iterable:
values.setdefault(element, []).append(other_value)
```
--------------------------------
### Override Chart of Accounts Properties Example (XML)
Source: https://www.odoo.com/documentation/12.0/developer/webservices/localization
This is an example in XML showing how to override specific properties for a Chart of Accounts, such as the Belgian PCMN. It sets particular accounts for receivables, payables, expenses, income, currency exchange, and transfers.
```xml
```
--------------------------------
### Alternative Odoo Page Creation with QWeb Template (XML)
Source: https://www.odoo.com/documentation/12.0/developer/howtos/themes
Demonstrates an alternative method for creating Odoo website pages by defining a QWeb template directly. This approach embeds the page content, including a snippet area, within the `` tag and associates it with a `website.page` record.
```xml
Our Services
Cloud Hosting
Support
Unlimited space
Services page
```
--------------------------------
### Add Demonstration Data for Academy Module
Source: https://www.odoo.com/documentation/12.0/developer/howtos/website
Defines demonstration records for the 'academy.teachers' model using XML. This data is loaded only in demonstration mode for testing purposes and is linked via the module's manifest file.
```xml
Diana PadillaJody CarrollLester Vaughn
```
--------------------------------
### Frontend Website Publish Management in XML
Source: https://www.odoo.com/documentation/12.0/developer/reference/mixins
This XML code integrates the 'website.publish_management' QWeb template into the frontend. It requires passing the record as 'object' and optionally setting 'publish_edit' and 'action' for frontend-backend linking and specifying the action ID.
```xml
```
--------------------------------
### Running Odoo Tests with Module and Exclusion Tags
Source: https://www.odoo.com/documentation/12.0/developer/reference/testing
This command-line example demonstrates running tests from a specific module ('sale') while excluding tests tagged as 'slow'. It uses the `odoo-bin` command with `--test-enable` and `--test-tags` to combine module selection and negative filtering.
```bash
odoo-bin --test-enable --test-tags 'sale,-slow'
```
--------------------------------
### Using the Action Manager with `do_action()`
Source: https://www.odoo.com/documentation/12.0/developer/howtos/web
Explains how to use the Odoo Action Manager from JavaScript to initiate various client-side actions, such as opening model views.
```APIDOC
## Using the Action Manager with `do_action()`
### Description
The Action Manager is a core Odoo Web component responsible for handling user-initiated actions, such as opening menus or reports. The `do_action()` method allows developers to programmatically trigger these actions from JavaScript.
### Method
`this.do_action(action_dict)`
### Endpoint
N/A (Client-side JavaScript API)
### Parameters
#### Path Parameters
N/A
#### Query Parameters
N/A
#### Request Body
- **action_dict** (Object) - Required - A dictionary describing the action to perform. Common types include `ir.actions.act_window`.
- **type** (String) - Required - The type of action (e.g., 'ir.actions.act_window').
- **res_model** (String) - Required for 'act_window' - The model to display.
- **res_id** (Number) - Optional for 'act_window' - Preselected record ID for form views.
- **views** (Array) - Required for 'act_window' - A list of `[view_id, view_type]` pairs defining available views.
- **target** (String) - Optional for 'act_window' - 'current' or 'new' to specify where the action should be displayed.
- **context** (Object) - Optional - Additional context data for the action.
### Request Example
```javascript
instance.web.TestWidget = instance.Widget.extend({
dispatch_to_new_action: function() {
this.do_action({
type: 'ir.actions.act_window',
res_model: "product.product",
res_id: 1,
views: [[false, 'form']],
target: 'current',
context: {},
});
},
});
```
### Response
#### Success Response (200)
N/A (Action manager performs client-side operations)
#### Response Example
N/A
```
--------------------------------
### WebRequest Class
Source: https://www.odoo.com/documentation/12.0/developer/reference/http
The base class for all Odoo Web request types, responsible for initialization and setup of the request object.
```APIDOC
## WebRequest Class
### Description
Parent class for all Odoo Web request types, mostly deals with initialization and setup of the request object.
### Parameters
- **httprequest** (werkzeug.wrappers.BaseRequest) - The original werkzeug Request object.
### Properties
- **httprequest** (werkzeug.wrappers.BaseRequest) - The original `werkzeug.wrappers.Request` object.
- **params** (Mapping) - Request parameters, generally provided directly to the handler method as keyword arguments.
- **cr** (Cursor) - Cursor initialized for the current method call. Accessing when using `none` authentication will raise an exception.
- **context** (Mapping) - Context values for the current request.
- **env** (Environment) - The `Environment` bound to the current request.
- **session** (OpenERPSession) - HTTP session data for the current http session.
- **debug** (bool) - Indicates if the current request is in “debug” mode.
- **registry** (Registry) - The registry to the database linked to this request. Deprecated since version 8.0: use `env`.
- **db** (str) - The database linked to this request. Can be `None` if the current request uses the `none` authentication.
### Methods
- **csrf_token**(time_limit=3600) - Generates and returns a CSRF token for the current session.
- **Parameters**
- **time_limit** (int | None) - Duration for which the CSRF token should be valid (in seconds). Default is 1 hour. `None` means valid as long as the user's session is valid.
- **Returns**
- ASCII token string.
```
--------------------------------
### Launch Wizard with ir.actions.act_window
Source: https://www.odoo.com/documentation/12.0/developer/howtos/backend
Defines an action to launch a wizard, typically displayed in a popup window. It can be triggered by a menu item or appear in contextual actions based on the 'src_model' field. Key fields include 'id', 'name', 'res_model', 'view_mode', and 'target'.
```xml
```
--------------------------------
### Modifying Controller Authentication
Source: https://www.odoo.com/documentation/12.0/developer/reference/http
Example of how to change the authentication requirement for a controller route in Odoo 12.0 by overriding the route decorator.
```APIDOC
## POST /some_url (User Authentication)
### Description
Modifies the '/some_url' route to require user authentication instead of public access.
### Method
POST
### Endpoint
/some_url
### Parameters
#### Query Parameters
- None
#### Request Body
- None
### Request Example
```json
{
"example": "Placeholder for request body if applicable"
}
```
### Response
#### Success Response (200)
- Requires the user to be logged in. Returns the result of the original handler if authenticated.
#### Response Example
```json
{
"example": "Result of original handler for authenticated user"
}
```
```
--------------------------------
### Creating a Menu Item to Launch a Client Action
Source: https://www.odoo.com/documentation/12.0/developer/howtos/web
This XML code defines a menu item in Odoo that, when clicked, will trigger the associated client action. It links the menu item 'action_home_page' to the parent menu 'petstore_menu', ensuring it appears in the correct location within the Odoo navigation structure and launches the defined client action.
```xml
```
--------------------------------
### Configure Odoo Model Field Attributes
Source: https://www.odoo.com/documentation/12.0/developer/howtos/backend
Example of configuring a 'name' field with the 'required=True' attribute. This makes the field mandatory when creating or updating records.
```python
name = field.Char(required=True)
```
--------------------------------
### Odoo Test Module Structure and Initialization
Source: https://www.odoo.com/documentation/12.0/developer/reference/testing
Demonstrates the standard directory structure for Odoo test modules and the necessary import statements in the '__init__.py' file to make test modules discoverable by the Odoo test runner. Ensures test modules are correctly organized and imported.
```text
your_module
|-- ...
`-- tests
|-- __init__.py
|-- test_bar.py
`-- test_foo.py
```
```python
from . import test_foo, test_bar
```
--------------------------------
### Define Odoo Model with Fields
Source: https://www.odoo.com/documentation/12.0/developer/howtos/backend
Example of an Odoo model with a 'name' field of type Char. This demonstrates how to define fields as attributes of the model class.
```python
from odoo import models, fields
class LessMinimalModel(models.Model):
_name = 'test.model2'
name = fields.Char()
```
--------------------------------
### Extend Theme Dependencies (Python)
Source: https://www.odoo.com/documentation/12.0/developer/howtos/themes
Example of how to add additional module dependencies to a theme's manifest file. This allows the theme to leverage features from other Odoo modules, such as e-commerce functionalities.
```python
'depends': ['theme_tutorial', 'website_sale'],
```
--------------------------------
### Model Querying with `query()`
Source: https://www.odoo.com/documentation/12.0/developer/howtos/web
Demonstrates the usage of the `query()` helper for simplified model data fetching, contrasting it with the `search()` and `read()` method combination.
```APIDOC
## Model Querying with `query()`
### Description
The `query()` method provides a more concise and readable way to fetch records from Odoo models compared to using `search()` and `read()` separately. It allows chaining methods like `filter()`, `limit()`, and `all()` for building and executing queries.
### Method
`model.query()`
### Endpoint
N/A (Client-side JavaScript API)
### Parameters
#### Query Parameters
- **fields** (Array) - Optional - A list of fields to fetch for each record. If omitted, all fields are fetched.
#### Request Body
N/A
### Request Example
```javascript
model.query(['name', 'login', 'user_email', 'signature'])
.filter([['active', '=', true], ['company_id', '=', main_company]])
.limit(15)
.all().then(function (users) {
// do work with users records
});
```
### Response
#### Success Response (200)
- **users** (Array of Objects) - An array of dictionaries, where each dictionary represents a record with its requested fields as keys.
#### Response Example
```json
{
"users": [
{
"name": "John Doe",
"login": "john.doe",
"user_email": "john.doe@example.com",
"signature": "JD"
}
// ... more user records
]
}
```
```
--------------------------------
### Overriding a Controller
Source: https://www.odoo.com/documentation/12.0/developer/reference/http
Example demonstrating how to override an existing controller's method in Odoo 12.0, adding custom logic before or after the original handler.
```APIDOC
## POST /some_url (Overridden)
### Description
Overrides the existing '/some_url' route to execute custom logic before calling the original handler.
### Method
POST
### Endpoint
/some_url
### Parameters
#### Query Parameters
- None
#### Request Body
- None
### Request Example
```json
{
"example": "Placeholder for request body if applicable"
}
```
### Response
#### Success Response (200)
- Executes custom logic (`do_before()`) and then returns the result of the original handler.
#### Response Example
```json
{
"example": "Result after do_before() and original handler execution"
}
```
```
--------------------------------
### Odoo XML: Try Loading Chart of Accounts Template
Source: https://www.odoo.com/documentation/12.0/developer/webservices/localization
This XML snippet demonstrates how to use the Odoo framework to attempt loading a specific chart of accounts template for the current company. It relies on the 'account.chart.template' model and expects a fully-qualified XML ID of the template to be provided.
```xml
```
--------------------------------
### Defining a Controller with @route
Source: https://www.odoo.com/documentation/12.0/developer/reference/http
Example of defining a new web controller in Odoo 12.0 using the @route decorator to specify a URL and authentication.
```APIDOC
## POST /some_url
### Description
Defines a public route at '/some_url' handled by the `handler` method, returning custom content.
### Method
POST
### Endpoint
/some_url
### Parameters
#### Query Parameters
- None
#### Request Body
- None
### Request Example
```json
{
"example": "Placeholder for request body if applicable"
}
```
### Response
#### Success Response (200)
- Returns the result of the `stuff()` function.
#### Response Example
```json
{
"example": "Result of stuff()"
}
```
```
--------------------------------
### Odoo Selection Field Widget with Placeholder
Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference
Demonstrates how to use the 'selection' widget for a 'tax_id' field and set a placeholder text to display when no value is selected. This is useful for guiding user input.
```xml
```
--------------------------------
### Create a Subclass using Odoo's Class System
Source: https://www.odoo.com/documentation/12.0/developer/reference/javascript_reference
Demonstrates how to create a subclass using Odoo's custom class system, which is inspired by John Resig. The `extend` method is used, and the `init` function serves as the constructor for new instances. This example defines an `Animal` class with basic properties and methods.
```javascript
var Class = require('web.Class');
var Animal = Class.extend({
init: function () {
this.x = 0;
this.hunger = 0;
},
move: function () {
this.x = this.x + 1;
this.hunger = this.hunger + 1;
},
eat: function () {
this.hunger = 0;
},
});
```