Skip to content
ERPForAll DocsDevelopment

    Native declared settings

    The SDK exports validated pure declarations in erp_sdk::settings. A native addon registers a factory:

    use erp_sdk::settings::{ScopeKind, SettingDecl};
    fn settings() -> erp_sdk::Result<Vec<SettingDecl>> {
    Ok(vec![SettingDecl::boolean("my_addon.enabled", "Enabled", ScopeKind::Global, true)?
    .access(&["base.group_system"], &["base.group_system"])?])
    }
    erp_sdk::setting_declarations!(settings);

    The macro binds the generated crate::ADDON descriptor, so its factory belongs to that actual addon.

    Base’s base.attachment_max_bytes has a narrow canonical System Parameter binding (ADR 0193). Its declared Settings value is read from ir_config_parameter, not duplicated in the scalar value table. Both edit surfaces use the global scope lock, revision and transactional audit. Do not add a second independent value or bypass the checked services with SQL. This is a specific base policy binding, not a generic addon parameter-binding API. Only installed registry addons contribute; group references must resolve and belong to the addon’s transitive dependency closure. Declarations are not generic parameter keys. Secret storage is excluded. Use the typed constructors for boolean, bounded string/integer/float and selection; no coercion occurs. A company declaration has exactly company scope, with no fallback to global values. A value of the wrong type or outside a setting’s floor or hard bound is refused, by validate and by every write through it, with one sentence that names the setting and its accepted bounds. A stored value that no longer fits its declaration is refused on read as Stored setting <key> is invalid.

    Call ir.config.setting.erp_describe(scope), then erp_read_values(scope, keys). Read results carry a canonical decimal scope revision. erp_write_values(scope, expected_revision, changes) accepts a nonempty batch of unique {key,value} entries and checks both group policy and current allowed companies. Keep its observed revision; stale writers must reload. All values, revision and audit commit together. Native consumers can call erp_addon_base::ir_config_setting::{describe,read_values,write_values} inside their existing transaction. No node-local value cache exists; invalidation is queued on the transaction.

    The base Settings menu/action points at the ordinary ir.config.setting service form. Its narrow XML is <form record_mode="service"><widget name="web.settings" scope_kinds="global,company"/></form>. The metadata producer translates this into ADR 0066’s typed web.form/web.settings nodes and must reject unknown attributes, duplicate/unknown scope kinds and service field children. XML source publication alone does not prove that producer or the browser integration is complete.

    Settings group by the key prefix: my_addon.enabled belongs to the my_addon app on the Settings page. The sidebar uses the first authorized root menu in server order whose owning module matches the target app, including its name and icon; an app without a matching root retains a neutral initial tile, and the page shows one app at a time; a search reaches every app. To give your addon its own Configuration > Settings entry, ship a service form that opens the shared page on your app, then a menu for it:

    <record id="settings_form" model="ir.ui.view">
    <field name="name">my_addon.settings</field>
    <field name="model">ir.config.setting</field>
    <field name="arch" type="xml">
    <form record_mode="service">
    <widget name="web.settings" scope_kinds="global,company" app="my_addon"/>
    </form>
    </field>
    </record>
    <record id="settings_action" model="ir.actions.act_window">
    <field name="name">Settings</field>
    <field name="res_model">ir.config.setting</field>
    <field name="view_mode">form</field>
    <field name="view_id" ref="settings_form"/>
    </record>
    <menuitem id="config_menu" name="Configuration" parent="my_addon_menu" groups="base.group_system" sequence="90"/>
    <menuitem id="settings_menu" name="Settings" parent="config_menu" action="settings_action" groups="base.group_system"/>

    An action that names an app opens settings for the current company when the app contributes company settings. Shared-only apps open their global scope.

    app must be an addon technical name (a lowercase letter, then lowercase letters, digits or _, at most 64 bytes); the view is refused at load otherwise, and web.addons does not accept it. When the page opens and no declared setting carries that prefix, the browser says so instead of showing another app. acceptance_notes ships this exact pattern under Notes > Configuration > Settings.

    Secondary or integration addons (such as sale_stock or stock_barcode) often contribute configuration that belongs logically on an existing application’s settings page rather than a standalone screen. In Odoo this is done with XML view inheritance on res.config.settings. In ERPForAll, addons configure this natively via the builder methods on SettingDecl:

    use erp_sdk::settings::{ScopeKind, SettingDecl};
    fn settings() -> erp_sdk::Result<Vec<SettingDecl>> {
    Ok(vec![
    SettingDecl::boolean("sale_stock.allow_returns", "Allow Spontaneous Returns", ScopeKind::Global, false)?
    .app("stock")?
    .block("Operations")?
    .sequence(20)
    .access(&["base.group_user"], &["base.group_system"])?,
    ])
    }
    erp_sdk::setting_declarations!(settings);
    • Namespace ownership: Setting keys always carry the declaring addon’s namespace (e.g. sale_stock.allow_returns). The declaring addon cannot declare keys prefixed with another addon.
    • Dependency closure: The target app specified in .app(...) must belong to the contributing addon’s transitive dependencies (and be installed). Targeting an undeclared or uninstalled module is refused at registry publication, using the same checks that validate security policy groups.
    • Section blocks: .block(...) specifies the titled section inside the app page (e.g., "Operations", "Pricing", "Users"). Settings without an explicit block default to "General".
    • Sequence ordering: .sequence(...) specifies the sort order. Blocks are ordered by their minimum sequence (then title), and settings within each block are ordered by sequence (then key). Lower numbers display first.

    Native declarations are this delivery’s scope. The WASM declaration mapping remains M2b and is not claimed as supported. addons/acceptance_notes contains the linked boolean example acceptance_notes.enabled, visible only after real installation. Its stored flag does not gate CRUD.

    A block can show read-only values (a count, a company’s name and address) and arrow links to a list, next to its settings (ADR 0174). These are not settings: they have no default, no write groups and no stored value, so they are a sibling declaration, PanelItemDecl, registered with its resolver:

    use erp_sdk::prelude::*;
    use erp_sdk::settings::{PanelItemDecl, PanelItemValue, SettingsScope};
    fn items() -> Result<Vec<PanelItemDecl>> {
    Ok(vec![
    PanelItemDecl::info("my_addon.open_orders", "Open Orders")?
    .block("Orders")?
    .sequence(10)
    .access(&["base.group_system"])?,
    PanelItemDecl::action_link("my_addon.manage_orders", "Manage Orders", "my_addon.orders_action", false)?
    .block("Orders")?
    .sequence(20)
    .access(&["base.group_system"])?,
    ])
    }
    fn resolve<'a>(
    env: &'a Env,
    tx: &'a mut Transaction,
    _scope: &'a SettingsScope,
    key: &'a str,
    ) -> erp_sdk::BoxFuture<'a, Result<PanelItemValue>> {
    Box::pin(async move {
    match key {
    "my_addon.open_orders" => {
    let domain = Domain::field("state")?.eq("open");
    let open = env.records("my_addon.order")?.search_count(tx, &domain, None).await?;
    let label = if open == 1 { "Open Order" } else { "Open Orders" };
    PanelItemValue::info(Value::Int(i64::try_from(open).map_err(|_| {
    Error::internal("count does not fit")
    })?))?
    .label(label)
    }
    _ => Err(Error::programming(format!("my_addon does not declare {key}"))),
    }
    })
    }
    erp_sdk::settings_panel_items!(items, resolve);
    • Kinds. PanelItemDecl::info(key, label) is an information row; its resolver returns PanelItemValue::info(scalar) (boolean, text, integer or finite float), optionally with .label(..) (1 to 256 bytes, for example the singular form) and .detail(..) (at most 1024 bytes, line feeds allowed). action_link(key, label, action, record) opens a window action; with record = true the resolver returns PanelItemValue::record(id) and the link opens that record. menu_link(key, label, menu) opens a menu. A plain link calls no resolver. A value out of bounds is a programming error, never cut.
    • Placement and audience. Same rules as settings: the key carries your addon’s prefix, .app(..) (default: the prefix), .block(..) (default "General"), .sequence(..) (default 100). .access(read) is required. An item shows in every scope unless you call .scope(ScopeKind::Company) or .scope(ScopeKind::Global). A key is unique across all settings and items.
    • Links are checked when the registry is published. The action or menu identity must name exactly one ir.actions.act_window or ir.ui.menu row of an addon in your dependency closure (your own data included). Otherwise installing or upgrading fails at ir.config.setting._register_hook with “Setting item references an unavailable action or menu.”. A release that adds a link to a new action needs the addon upgrade that loads that action.
    • Values use the caller’s rights. The resolver gets the caller’s own environment, never an elevated one: count with env.records(..) so access rules and record rules apply. Each call runs in a savepoint. Return an Access error to leave the item out for that caller; any other error fails the whole description. The scope tells you which company a company-scope page describes.
    • Wire. ir.config.setting.erp_describe(scope) returns the rows in items, sorted by key, beside declarations. erp_read_values and erp_write_values refuse an item key like an unknown key. The web client renders information and link rows alongside declarations.

    Base declares the General section this way (addons/base/src/settings_general.rs, SPEC-SETGEN): Users, Languages and Companies blocks with the active internal users, the active languages, the company’s name and address with an “Update Info” record link, the number of companies, and links to the lists that manage them. Add your own rows to those blocks by targeting app base and the block title.

    The native theme_office_blue addon demonstrates a global selection with internal-user read and system-administrator write policy. Install it explicitly; it is not auto-installed. Its theme_office_blue.appearance key offers default and office-blue. Settings saves use the same CAS and audit API as any declared setting. Refresh the application after saving; other open browsers see the database-wide choice on their next refresh. Uninstall removes the declaration, and fresh clients use Default without reading any orphaned value. Its CSS is declared as an installed tenant asset, not a browser preference.

    The web client decodes erp_describe.items separately from scalar declarations. Only declaration keys enter erp_read_values and erp_write_values; information and links never enter the edit baseline or CAS changes. Rows share app/block placement and sequence/key ordering. An item-only app is visible, and base opens first unless the service widget explicitly selects an app. Information values and multiline detail are rendered as text. Search includes them without interpreting markup.

    Links use the shell-provided ServiceEnvironment.settingsNavigation capability (ADR 0184, Proposed). roots contains authorized root-menu presentation snapshots in server order; openTarget accepts the generated SettingsLinkTarget union and runs the normal action/record/menu route with departure checks. A matching module is provenance only. If several roots match, the first wins independently of a personal home-menu order. A child menu never supplies an app identity. Base keeps the General Settings content heading while its rail uses the root-menu name.

    A custom Settings host may pass { navigation: { roots, openTarget } } as settingsView’s final options object. A description with links requires this capability. Scalar-only and information-only standalone hosts need none. A custom dispatcher must preserve authorization, dirty-state decisions and operation guards; it must not mark the service busy before asking the shell to leave, because departure may need to save that service.

    Scalar setting keys may contain nested identifier segments, such as base.jobs.chunk.default.lock_ms; the first segment still owns the key. Policy group and menu/action external IDs retain their existing grammar. Use .help(text) for bounded plain-text units and range explanations. Help-bearing boolean, text and numeric controls offer Use default, which edits the field normally; Save persists that value with the same CAS and audit.

    Register interdependent values with erp_sdk::setting_groups!(factory). The factory returns validated SettingGroupDecl::new(identity, member_keys, validator) declarations. A validator is a synchronous fn(&BTreeMap<String, Value>) -> Result<()>; it receives complete typed members and no environment, transaction or mutable values. Membership is unique, bounded, owned by the declaring addon and of one scope. Publication validates default snapshots. Overlapping groups expand to a bounded complete member closure.

    The Settings service checks authorization for expanded reads, locks the exact scope, compares the observed revision, and validates the complete proposed snapshot before any value/audit write. Unchanged members and restored defaults participate. A native callback cannot broaden read or write authority. Corrupt rows fail rather than becoming defaults. Keep predicates pure and return errors naming the relevant setting.

    Base registers the Shared jobs catalogue as the base.jobs group. Its numeric defaults and bounds come from erp_sdk::jobs::Setting; is_shared() distinguishes database policy from node capacity. Native composition injects DatabaseJobSettingsSource; each admission reads committed policy and each claimed run retains its snapshot. Settings changes publish an empty jobs wake only with their commit. Polling recovers missed hints; a failed policy read refuses new admission.

    A technical value (a limit, bound, timeout, size, batch, retry or interval) is not a Settings page row. Declare it as a system parameter: it lives in ir.config_parameter under its key and shows in Technical, System Parameters (ADR 0227). Use a SettingDecl for a business choice an administrator makes on the Settings page; one key is either a setting or a parameter, never both.

    use erp_sdk::settings::{ParameterDecl, SettingGroupDecl};
    use erp_sdk::Value;
    fn parameters() -> erp_sdk::Result<Vec<ParameterDecl>> {
    Ok(vec![
    // key, label, default, (floor, hard bound)
    ParameterDecl::integer("my_addon.import_batch", "Import batch", 500, (1, 10_000))?,
    ParameterDecl::integer("my_addon.retry_base_secs", "Retry base (seconds)", 5, (1, 600))?,
    ParameterDecl::integer("my_addon.retry_cap_secs", "Retry cap (seconds)", 300, (1, 3_600))?,
    ParameterDecl::boolean("my_addon.strict_import", "Strict import", true)?,
    ParameterDecl::string("my_addon.partner_token", "Partner API token", "", 256)?.secret(),
    ])
    }
    fn groups() -> erp_sdk::Result<Vec<SettingGroupDecl>> {
    Ok(vec![SettingGroupDecl::new(
    "my_addon.retry",
    &["my_addon.retry_base_secs", "my_addon.retry_cap_secs"],
    |values| match (&values["my_addon.retry_base_secs"], &values["my_addon.retry_cap_secs"]) {
    (Value::Int(base), Value::Int(cap)) if base <= cap => Ok(()),
    _ => Err(erp_sdk::Error::validation(
    "my_addon.retry_base_secs must not exceed my_addon.retry_cap_secs.",
    )),
    },
    )?])
    }
    erp_sdk::system_parameters!(parameters, groups); // or system_parameters!(parameters)

    The constructors are boolean, string (bound 1 to 65,536 bytes), integer and float (floor and hard bound, inclusive), and selection. Add .validator(fn) for a pure check beyond the bounds (it must accept the default), .secret() for a credential and .without_default_row() (below). A constructor refuses a bad declaration with a message naming the key:

    • the default must lie between the floor and the hard bound;
    • every number needs a floor of at least 1, whatever its key is called. Zero never means “unlimited”, and an empty value means the default. A number whose 0 or fraction has a meaning (a switch-off threshold, a ratio) is declared with integer_floor_below_one or float_floor_below_one, which take the reason as their last argument.

    For example:

    ParameterDecl::integer_floor_below_one(
    "my_addon.warn_after", "Warn after failures (0: never warn)", 3, (0, 100), "0 turns the warning off",
    )?

    At registry publication (install, upgrade, server start) the key must start with your addon’s name, and must not be declared twice by any addon, setting or Settings page item (Parameter <key> has more than one declaration.). A group may only name parameters of the same addon, and its validator must accept the defaults.

    What the framework does with the declaration:

    • Default row. Each declared key without a row gets one holding its default, so it is visible in System Parameters from install. An existing row is never overwritten. Do not also ship a data record for a declared key: the declaration is its default row. Use .without_default_row() when the absent value follows something a stored row would freeze: another key (base’s per-login cooldown is four times the per-address one) or a floor a later release raises (the password hashing costs).
    • Stored rows are checked at publication. Install, upgrade and server start read every declared key’s row: stored text outside its declaration or a group it breaks stops the publication with Stored parameter <key> is invalid. or the group’s message. A migration that moves a value onto a parameter checks the same.
    • Every write is checked. The System Parameters form, ORM writes, set_str/set_int and data files all go through the declaration: <key> takes <bounds>. for a value of the wrong kind or out of bounds (the value is not echoed), then your validator and the groups the key belongs to. The whole batch rolls back. Emptying a row resets the key to its default.
    • Audited. An administrator’s change takes the global Settings lock, advances the global Settings revision and writes an ir.config.setting.audit row (key, old and new value, actor) in the same transaction, only when the effective value changes (writing the default’s text into an empty row changes nothing). A secret’s row records (secret) for both values. Superuser-mode writes of framework code (install, default rows) are not audited, and a migration writes its own rows with actor migration:<addon>@<version>.
    • Protected. A declared key’s row cannot be deleted or renamed, in any mode; the refusal is a validation error naming the key.
    • Secrets. A .secret() parameter is hidden from every caller outside superuser mode: no search, count, read, group or domain on value returns or matches its row, and get_str, set_str, a create or a rename onto the key are refused naming erp_replace_secret. The row stays hidden after your addon is uninstalled (while its code is linked). Administrators replace the value with ir.config_parameter.erp_replace_secret(key, value), which runs the same checks and returns nothing. Your addon still reads it with the typed reads below. Base also hides a closed list of credentials Odoo addons keep as parameters (erp_addon_base::ir_config_parameter::SECRET_KEYS, database.secret and database.uuid among them).
    • Typos are refused. Once your addon declares a parameter, a write of an undeclared key under your prefix is refused (Parameter <key> is not declared by an installed addon.). Keys outside every declaring addon’s prefix stay free text for integrators, as in Odoo. When your addon is uninstalled its rows become plain text again.
    • Typed reads. Read with erp_sdk::params::{get_int, get_float, get_bool, get_str}(tx, &crate::ADDON, key); pass your own crate::ADDON itself, a copy of a descriptor is refused. The read is elevated (your code reads its own configuration; the caller needs no group), sees pending writes of the transaction, and returns the declared default for a missing or empty row. Stored text that does not fit the declaration fails with Stored parameter <key> is invalid.; it never falls back to the default. You may read keys of your addon and of the addons it depends on; any other key, an undeclared key or a getter of the wrong kind is a programming error naming the key.
    let batch = erp_sdk::params::get_int(tx, &crate::ADDON, "my_addon.import_batch").await?;

    Base declares its own parameters the same way: the authentication and session keys (password.hashing.*, base.login_cooldown_*, sessions.*), attachments.*, base.partition_upkeep_interval_secs, base.default_max_email_size, the image limits base.image_max_pixels, base.image_max_bytes, base.image_jpeg_quality and base.image_decode_timeout_secs (Binary and image fields) and the programmatic API key switch and limit. Those keys keep the write-time checks and messages they had before. database.* keys are not declared; database.secret and database.uuid are secrets and cannot be replaced over RPC. Settings administrators (base.group_system) have full access to System Parameters; other users have none. The System Parameters screen does not yet show a declared key’s label, bounds, a “reset to default” action or a “replace secret” action. Inventory declares its stock unit limits (stock.quant_*, with the group stock.quant_retry_backoff) the same way; see Stock quant engine.

    Moving a Settings value to a parameter. Keep the key and its bounds, remove the SettingDecl, add the ParameterDecl, raise your addon’s version and add a post migration for that version (it runs before the new registry is published, so before the default rows exist). Copy each stored global ir_config_setting_value row of the key into ir_config_parameter as canonical text, check it with the declaration’s check_text (a refusal stops the upgrade naming the key; never clamp) and run the parameter groups on the final values. Do not advance the Settings revision: the effective value did not change. Leave the source rows in place for one release so a rollback still reads them. addons/stock/src/migrations.rs (quant_policy_parameters) is a worked example.

    Inventory declares seven company values and a database-global barcode separator (its stock unit limits are system parameters, see above). Read them through ir.config.setting.erp_read_values with the explicit scope and use erp_write_values with the observed revision. There is no mirror on company rows or arbitrary parameter fallback.

    KeyScopeDefaultDomain
    stock.picking_policyCompanydirectdirect, one
    stock.horizon_daysCompany3651–3650 days
    stock.annual_inventory_monthCompany12Month keys 1–12
    stock.annual_inventory_dayCompany31Valid day of the selected month, February at most 28
    stock.stock_move_email_validationCompanyfalseBoolean
    stock.stock_text_confirmationCompanyfalseBoolean
    stock.stock_confirmation_typeCompanysmssms
    stock.barcode_separatorGlobalcomma1–16 UTF-8 bytes, no control characters

    The month and day form one native settings group. A partial change validates the stored or default sibling under the scope lock; an impossible date is refused rather than adjusted. A failed batch preserves the prior values, revision and audit. Inventory managers can read company values; only settings administrators can save. The global separator is administrator-only.

    An effective stock.picking_policy change updates the active operation types of that company in the same transaction. Compare-and-save behavior, the RPC response and existing Settings permissions are unchanged. The native _apply_value_changes hook receives the exact scoped company and only the changed effective values. Consumer failures roll back the batch.

    Key-level refusals have kind Access, HTTP status 403, and the sentence Setting <key> is unavailable or access is denied. The key comes from the request. Unknown, inaccessible, wrong-scope and information/link keys use the same refusal path and do not reveal which condition applied. A denied validation-group sibling is reported using an original request key, not its hidden identity. Scope and model-level authorization errors keep their conditions and kinds; an inaccessible Settings company asks you to choose a company available to your account.

    Feature controls shown as unavailable are information items, never scalar declarations. Read and save only the declaration keys returned for the scope. Module links target Inventory’s own Addons service action; saving settings never installs a module. Operational consumers of these values are still being delivered; the page’s help states where a saved value has no effect yet.