Odoo can I display a field of a many2one related field without duplicating it in the model using the related flag - odoo-14

Say, in odoo I have a Model A with a many2one field to model B.
Model B has a field "city".
Now I want to create a form for model A in which I want the "city" field of model B.
I can do this by adding the city field of Model B to model A as well and giving it the related flag.
b_city = fields.Char(related='b_id.city', depends=['b_id'])
But I dont like this because than I have to add this field to my model. I would prefer if can do this without creating this field. Is this possible?
-----------Edit---------------
Something that I'm looking for is like this:
<page string="Offers">
<field name="offer_ids">
<tree>
<field name="price"/>
<field name="partner_id"/>
<field name="validity"/>
<field name="date_deadline"/>
<button name="accept" type="object" icon="fa-check"/>
<button name="reject" string="X" type="object" icon="fa-xmark"/>
<field name="status"/>
</tree>
</field>
</page>
This a page in a form where the corresponding model has a one2many field which is being displayed in a tree view. Now, I want to the other way around. I want to display in a form some fields of another model to which the there is a many2one field.
Is it possible to do this in the the xml view?

There is no way to do that in Odoo unless using related field.
Check Odoo ORM documentation

USING PYTHON CODE :
Example 1:
invoice_partner_icon = fields.Char(compute='_compute_invoice_partner_display_info', store=False, compute_sudo=True)
#api.depends('partner_id', 'invoice_source_email')
def _compute_invoice_partner_display_info(self):
for move in self:
vendor_display_name = move.partner_id.display_name
if not vendor_display_name:
if move.invoice_source_email:
vendor_display_name = _('From: ') + move.invoice_source_email
move.invoice_partner_icon = '#'
else:
vendor_display_name = _('Created by: %s') % (move.sudo().create_uid.name or self.env.user.name)
move.invoice_partner_icon = '#'
else:
move.invoice_partner_icon = False
move.invoice_partner_display_name = vendor_display_name
OR USING UI :
As admin, You can create a new field in Model B which is related to model A without storing it in the database : in App Settings, switch to debug mode by adding "?debug=1" in your url, reload the page, then go to the new Technical Menu-tab > Fields.
Then, create your new related field using the panel "Advanced Properties" Related Field: ...
and then uncheck [ ] Stored

Related

How to not allow Many2many to be able to remove its element in form view?

I have a many2many field that represents a list of student. I want to only add student to that list but not remove any students from that list (in form view). Is it possible to implement that?
I think it's possible to do it. You need to override the #write method. Each time that an update will be made on your object, you need the compare the actual length of your many2many field current_length and the new length of students made by the update new_length.
If new_length > current_length, it's means that the update is an adding, so you can consider the changes. Otherwise, it's means that the update is a removing, so you just need to ignore the changes.
Please find below, an exemple of implementation :
#api.multi
def write(self, values):
current_length = len(self.student_list)
new_length = len(values['student_list'])
if current_length > new_length:
\* Removing of students *\
values['student_list'] = self.student_list
res = super(Object, self).write(values)
return res
Note that you can go further by making another comparaison between the ids of the current and new list, in order to be sure that the students are the same.
It s not possible using the many2many_tags widget, but using the xml tree view as part of your Form view, you can add the delete-attribute on the tree-node inside the scope of your own field:
<form>
<notebook>
<sheet>
<page string="Graduated" name="gratuated_students">
<field name="students_ids" >
<tree string="Students" editable="bottom" delete="0" >
<field name="name"/>
<field name="birthday"/>
<field name="score" readonly="1"/>
</tree>
</field>
</page>
</notebook>
</sheet>
</form>
If this view comes from an odoo's module (no custom module): you'd rather inherit this view and add the attribute "delete=0" to the existing student_ids field:
<xpath expr="//form[1]/sheet[1]/notebook[1]/page[1]/field[#name='students_ids']/tree[1]" position="attributes">
<attribute name="delete">0</attribute>
</xpath>
Otherwise, if you really want to use the many2many_tags widget and if your are experienced with odoo's js-framework, you could develop your own option "no_delete" on the basis of the following OCA module:
https://odoo-community.org/shop/web-m2x-options-2661#attr=10772

conditions for a field to appear in odoo 14

I'd like field A to appear only if field B has a given value
field B doesn't belong to the same model, it belongs to a model connected through a many2one relationship
How do I write the contents of the attrs attribute for field A in the form ?
Until now I used
<field name="A"...
attrs="{'invisible': [('B', '=', 'some_value')
But until now both A and B belonged to the same model
Field used in attrs must be present in view
You can't use dotted field names because Odoo will raise an error if the field name contain . when validating the view definition:
Invalid composed field %(definition)s in %(use)s (attrs.invisible ...)
There is an exception for list sub-views (One2many/Many2many display in a form view) where you can use parent.field_name
ok, I reply to myself
First, in the model:
field_B = field.fieldtype(related='many2one_field.field_b')
Then, in the form view:
<field name="field_B" invisible="1"/>
and then
<field name="field_A" ...
attrs="{'invisible': [('field_B', '=', 'some_value')]}">

How to conditionally hide rows in One2Many field tree in a form view? [duplicate]

In my module I want to filter one2many records based on current date.
This is my xml code
<field name="record_ids" domain="[('end_date', '>', cur_date)]">
<tree string="records_tree">
<field name="record_id"/>
<field name="record"/>
<field name="start_date"/>
<field name="end_date"/>
</tree>
</field>
cur_date is a functional field I added to get current date.
My problem is records are not filtered in the view. Also it doesn't show any error message
you are define the domain in the XML file .
so this domain it's not work .
please define in the .py file .
For Example :
'record_ids':fields.one2many('model_name','model_id','Record',domain=[('end_date', '>=', 'cur_date')])
here the cur_date you need to define one function field which show the current date.
So Please check this may be it's help full to you :).
I also faced this problem, and the solution is put domain in .py file, in .xml domain is not working properly.
import_transaction_log_ids = fields.One2many(comodel_name = 'transaction.log','sale_order_id', string = 'Import Transaction Log',domain=[('operation_type','=','import')])
in example operation_type field is in transaction.log model.
Write domain in end_date field, like this:
<field name="record_ids" >
<tree string="records_tree">
<field name="record_id"/>
<field name="record"/>
<field name="start_date"/>
<field name="end_date" domain="[('end_date', '>', cur_date)]"/>
</tree>
</field>
i think it will help you..
you can pass only those field in domain those are store in Database.
So in that case cur_date is not store in Database.
Then also you need to pass into domain so you need to store cur_date field from py.
first of all, one2many fields are not for selection purpose. We can create the new records or update the existing records in one2many field. so we cannot apply domain to a one2many field.
eg: sale_order_line field in sale.order
moreover one2many fields, functional_fields [**if store=True not specified ] wont store in the table.
Many2one or Many2Many are used for selecting the records [ as well as creating new ones ], so here we can apply domain and we can restrict the user to select some type of records
eg: Many2one- product_id field in sale.order.line
many2many - user_ids field in res.users
So, in order to get your task, try many2many and apply domain, then the records will be filtered
domain contains 'field name' 'expression' 'value'.
instead of value you given a field
<field name="record_ids" domain="[('field', 'expression', value)]">
Add it in python:
Eg:
xn_cutting_ids = fields.One2many('mrp.bom.line', 'bom_id', 'Cutting Lines', domain=lambda self:[('xn_stage','=','cut')])
Use domain = lambda else there is a chance of error while using string values in domain.
Here xn_stage is in mrp.bom.line model.
On Odoo V11
Define a function that returns a domain in the one2many field definition.
class GroupContract(models.Model):
_name = 'group.contract'
#api.multi
def _domain_move_ids(self):
"""Odoo default domain for many2one field is [('contract_id', '=', self.id)].
This function adds new criteria according to your needs"""
res = []
if len(self) == 1: # do not compute in tree view
ids = self.env['stock.move'].search([
('state', '=', 'done'),
('date', '>=', self.start_date),
('date', '<=', self.end_date)
]).ids # choose your own criteria
res = [('id', 'in', ids)]
return res
start_date = fields.Date(string="Start date", required=True)
end_date = fields.Date(string="End date", required=True)
move_ids = fields.One2many(comodel_name='stock.move', inverse_name='contract_id', string="Moves",
domain=lambda self: self._domain_move_ids())

i have a many2many table,But i need to give domain as only the partner's record in the model needs to be shown in the many2many table

class HealthProfileInherit(models.Model):
_inherit = 'health.profile'
health_profile_health_test_id = fields.Many2many('health.test',
string ='Laboratory Test')
this the field connecting the 2 tables, how will give domain here? Do I wanna write a function or can give domain inside the field?
The following domain:
domain="[('partner_id', '=', partner_id)]"
will filter records shown in the popup list after you click on the add item button link. only the test records with the profile partner will be visible.
String domains are supposed to be dynamic and evaluated on the client-side only.
By default, users can create records from the popup list and they can select any partner in the partner_id field.
If you want to disable the creation option from the popup list use the no_create option:
options="{'no_create': True}"
If you want to keep the create button and force users to select the profile partner, you can create a new form for the health.test model and set the partner field invisible then pass the default partner value in context and force the many2many field to use that form.
<field name="health_profile_health_test_id"
domain="[('partner_id', '=', partner_id)]"
context="{'form_view_ref': 'module_name.health_test_form', 'default_partner_id': partner_id}"/>
Remember that the form view with the lowest priority will be used as the default form view (The default priority value is 16):
Example:
<record id="health_test_form" model="ir.ui.view">
<field name="name">health.test Form</field>
<field name="model">health.test</field>
<field name="priority" eval="20"/>
<field name="arch" type="xml">
<form>
<group>
<field name="partner_id" invisible="True"/>
....
</group>
....
</form>
</field>
</record>
Edit:
String domains are dynamic and evaluated in client-side, for example the "[('partner_id', '=', partner_id)]" string domain will be evaluated to [('partner_id', '=', 26)] and if the list has already selected records, the records will be excluded using ['!', ['id', 'in', list_of_ids]].
But when passing the domain as a list with the many2one field reference, the value will be of type Many2one and the server should raise a RecursionError when trying to get field attributes (tested in v12, v13).
If you look in the Odoo source code you will find many examples using a list domain but with simple values like booleans, strings, etc.

Odoo show values of selected Many2one record

In my custom view, there is a field Many2one, next to it I would like to show values of that item as information in view after a serial_number is selected.
# model.py (newApi)
serial_number = fields.Many2one(comodel_name="stock.production.lot", string="Serial Number", required=True)
# view.xml
<field name="serial_number" options="{'no_open': True, 'no_create': 1, 'no_create_edit': 1}"/>
<div>
<span>serial_number.product_id.name</span>
<span>serial_number.product_id.description</span>
</div>
How I have to do correctly?
As per your requirement you need to use widget='selection' This will make many2one field as a selection field.
try with this:
<field name="serial_number" widget='selection'/>
USE related to do this :
Create a related fild in the model that have many2one relation
like this
field_name = fields.Char(string="Selected value", related="Field_name_in_co_model")
than put it in your form with readOnly :
<field name="field_name" readonly="1" />
when the user select an item the information of the selected record will show automaticly in the fields sorry for my english if you didn't undertand tell me i will give an exemple
you can even put it in tree form it's greate thing