Change many-to-one domain based on selection field - odoo

I want to change the domain of many-to-one field based on user selection, selection field have to options (code, phone), but the domain does not change and get only the default value:
#api.onchange('search_by')
def _get_partner(self):
partners = self.env['customer.regist'].search([('name','!=','New')])
partner_list = []
partner_list2 = []
for rec in partners:
partner_list.append(rec.name)
partner_list2.append(rec.phone)
res = {}
if self.search_by == 'code':
res['domain'] = {'search_value': [('name', 'in', partner_list)]}
if self.search_by == 'phone':
res['domain'] = {'search_value': [('phone', 'in', partner_list2)]}
return res

I didn't test the code but from the look of it the domain will always contain all customer.regist records (except the ones with the name 'New' of course). You are going through all the records and adding their phones / names to a list and then say that the phone / name must be included in that list. So you will always have all of them.

Related

How to extend search record to also look at custom Many2Many field(s)?

In this image, there is a product search record that will search for name and default_code. I need to make it so that it will also look at my custom Many2Many field.
This is the field in the inherited model.
product_list = fields.Many2many("product.list", string="Product List")
The custom model only has _name, _description, and name variables.
The question is how to make the search to also look at all of the possible Many2Many data of this field.
I have tried this in the inherited model:
#api.model
def name_search(self, name='', args=None, operator='ilike', limit=100):
res = super(product_template_inherit, self).name_search(name='', args=None, operator='ilike', limit=100)
ids = self.search(args + [(name, 'in', 'product_list.name')], limit=limit)
if ids:
return ids.name_get()
return res
Nothing happens to the search. It still searches using the same behavior regardless of the code above.
Summary: I need to be able to search product by product list (custom Many2Many field inherited in the product.template model)
=============================================
UPDATE
Current code from what I have been trying is now this.
#api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
args = args or []
if operator == 'ilike' and not (name or '').strip():
domain = []
else:
domain = ['|', ('name', 'ilike', name), ('product_list.name', 'ilike', name)]
product_ids = self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)
return self.browse(product_ids).name_get()
However, it looks like it still searches using the same old fields. It does not change to behave as my function is written.
You can compute the search domain then return the result of the _search method.
The fleet module already uses the same logic to search vehicles using the driver name, you have just to replace the driver_id with product_list:
class ProductProduct(models.Model):
_inherit = 'product.product'
#api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
args = args or []
if operator == 'ilike' and not (name or '').strip():
domain = []
else:
domain = ['|', ('name', operator, name), ('product_list.name', operator, name)]
return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)

How to creat records in odoo tree view onclick button?

please help
I need when I click Enregistrer Button to create those fields in the tree view on the bottom
for this example, I have quantity equal 12 so I need 12 lines to be created on the tree view with the values on the wizard view
the wizard code :
class LinesWizard(models.Model):
_name = 'bons.wizard'
w_contrat_name = fields.Many2one('contrat.contrat', string='Contrat')
w_contrat_line = fields.Many2one('contrat.lignes', string='Ligne contrat')
w_product_name = fields.Many2one('product.product', string='Produit')
w_po_number = fields.Char(string='Numero PO')
w_qtt = fields.Float('quantite', related='w_contrat_line.quantity')
w_prix = fields.Float(string='Prix unitaire', related='w_contrat_line.unit_price')
#api.onchange('w_contrat_name')
def on_change_contrat_name(self):
if self.w_contrat_name:
self.w_contrat_line = False
return {'domain': {'w_contrat_line' : [('ligne_ids', '=', self.w_contrat_name.id)]}}
else:
return {'domain': {'w_contrat_line': []}}
In your function for the Enregistrer button, you can use below code to get the active sale.order ID.
session_id = self.env['sale.order'].browse(self._context.get('active_id'))
Then in the same function, simply create and add your rows.
session_id.write({
'your_tree_ids': [(0, False,
{
'w_contrat_name': self.w_contrat_name,
'w_product_name': self.w_product_name,
'etc': 'etc...'}
)] * int(self.w_qtt) # assuming rows to be added are the same, create a list of w_qtt quantity of (0, _, values), since your qty is a float, need to convert to int first
})

how get id with onchange for filtering

how can i retrieve the value of a many2one field or its ID from another model
for exemple:
class Contrat(models.Model):
_name = 'facturation.contrat'
contrat_parent_id = fields.Many2one('facturation.contrat', string='Numéro Contrat Client',
domain=[('is_prestataire', '=', False)])
class Lot(models.Model):
contrat_id = fields.Many2one('facturation.contrat', ondelete='cascade')
articlecontrat_ids = fields.Many2many('facturation.articleouvrage',string='Article Lot')
91/5000
i want that when i change contrat_parent_id i get it back to use it and filter my articles for field 'articlecontrat_ids'
here you need to use onchange event i'm assuming that facturation.articleouvrage have a m2o field named contrat_id
# in onchange event always put the name of the field that trigger the event
#api.onchange('contrat_parent_id ')
def onchange_contrat(self):
"""update the domain when we change the contrat"""
if self.contrat_parent_id :
# always check if the field is not empty
# return the domain like this but i don't know what you need exactly
return {'domain': {'articlecontrat_ids ' : [('contrat_id ', '=', self.contrat_parent_id.contract.id)]}}
else: # remove the domain
return {'domain': {'articlecontrat_ids ' : []}}
if you want to remove all records when user change the contrat_id but i think you make the user ungry
to reselect all this records.
self.articlecontrat_ids = [(5, 0, 0)]

Odoo 10 XMLRPC How to map one2many and many2one

I have recently been doing some development in python 2.7 with Odoo 10 API using XMLRPC.
My questions are:
How do I write a one2many field to a field in odoo via xmlrpc
How do u write a many2one field to a field in odoo via xmlrpc
Many thanks your help is much appreciated!
Samuel
For Many2one fields you can simply use the ID of the record:
my_partner_id = 1 # or use a search to find the correct one
id = models.execute_kw(db, uid, password, 'sale.order', 'create', [{
'partner_id': my_partner_id,
}])
Many2many or One2many fields are a bit special. There are some magic triplets in Odoo, you have to use with such fields -> Model Reference/CRUD/write(vals).
For example if you want to add a tag to a customer (Many2many field):
my_tag_id = 42 # or use a search to find the correct one
id = models.execute_kw(db, uid, password, 'res.partner', 'write',
[my_partner_id], [{
'category_id': [(4, my_tag_id)],
}])
Or if you want to delete all tags:
my_tag_id = 42 # or use a search to find the correct one
id = models.execute_kw(db, uid, password, 'res.partner', 'write',
[my_partner_id], [{
'category_id': [(5,)],
}])
Or if you want to substitute all tags by some others:
my_tag_id1 = 42 # or use a search to find the correct one
my_tag_id2 = 7 # or use a search to find the correct one
id = models.execute_kw(db, uid, password, 'res.partner', 'write',
[my_partner_id], [{
'category_id': [(6, None, [my_tag_id1, my_tag_id2])],
}])
Create Activity (One2many field) in CRM form using Php API In #v11 Odoo Community:
$opportunity_id = 13; (Lead in which you create activity)
$user_id = 1; (User, for whom you assign task)
$c = $_POST["loading_time"]; (Deadline date which you have to set from php)
$enddate = date("Y-m-d H-i-s", strtotime($c));
$model = 'crm.lead';
$res_model_id = $models -> execute_kw($db, $uid, $password,
'ir.model', 'search', array(array(array('model', '=', 'crm.lead'))));
print_r($res_model_id);
$activity_type_id = $models -> execute_kw($db, $uid, $password,
'mail.activity.type', 'search', array(array(array('name', '=', 'Todo')))); (this is activity type like Todo,Call,Email,etc....)
print_r($activity_type_id);
$product_attribute_line = $models -> execute($db, $uid, $password,
'mail.activity', 'create',
array('model'= > $model,
'res_id'= > $opportunity_id,
'note'= > $_POST["question"],
'user_id'= > $user_id,
'date_deadline'=> $_POST["loading_time"],
'res_model_id'= > $res_model_id[0],
'summary'= > $_POST["subject"],
'activity_type_id'= > $activity_type_id[0],
'activity_ids'= > array(array(6, 0, array($opportunity_id))) ));
(activity_ids is a one2many field which will create activity)
Important:
To Create One2many field You must have to pass related many2one Id
You can see in image also by refer following image:
enter image description here

How to rename partner ledger report in odoo8?

Partner ledger report name is 'account.report_partnerledger.pdf' by default. I want to change it to customer name (eg: john.pdf if customer name is john). How to do this?
Install report_custom_filename.
Go to Settings > Actions > Reports and search for Partner Ledger.
Fill in the Download filename field. This field is evaluated as jinja2 template with objects being a list of browse records of the records to print, and o the first record. If your model contains a name field, you might write something like ${o.name}_report.pdf as filename.
Possible through complex coding but thanks to odoo community we have one module named
report_custom_filename
which will let you do this by little configuration
Install 'report_custom_filename' module and make the following changes in report_routes method
def report_routes(self, reportname, docids=None, converter=None, **data):
cr, uid, context,registry = request.cr, request.uid, request.context,request.registry
response = super(ReportController, self).report_routes(
reportname, docids=docids, converter=converter, **data)
if docids:
docids = [int(i) for i in docids.split(',')]
report_xml = http.request.session.model('ir.actions.report.xml')
report_ids = report_xml.search(
[('report_name', '=', reportname)])
options_data = simplejson.loads(data['options'])
partner_id = options_data.get('ids')
for report in report_xml.browse(report_ids):
if not report.download_filename:
continue
#objects = http.request.session.model(report.model).browse(docids or [])
objects = request.registry[report.model].browse(cr, uid, partner_id, context=context)
customer_name = str(objects.name)
generated_filename = email_template.mako_template_env\
.from_string(report.download_filename)\
.render({
'objects': objects,
'o': customer_name,
'object': objects[:1],
'ext': report.report_type.replace('qweb-', ''),
})
response.headers['Content-Disposition'] = content_disposition(
generated_filename)
return response