Hide field form fields_view_get - odoo

def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
#override of fields_view_get in order to change the label of the process button and the separator accordingly to the shipping type
if context is None: context={}
res = super(stock_partial_picking, self).fields_view_get(cr, uid, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) type = context.get('default_type', False)
if type: doc = etree.XML(res['arch'])
for node in doc.xpath("//button[#name='do_partial']"):
if type == 'in':
node.set('string', _('_Receive'))
elif type == 'out':
node.set('string', _('_Deliver'))
i want to hide qty,expire_date field
for node in doc.xpath("//separator[#name='product_separator']"):
if type == 'in':
node.set('string', _('Receive Products'))
elif type == 'out':
node.set('string', _('Deliver Products'))
res['arch'] = etree.tostring(doc)
return res

Set the "invisible" = "1",
for node in doc.xpath("//separator[#name='product_separator']"):
if type == 'in':
node.set('string', _('Receive Products'))
node.set('invisible', '1')
elif type == 'out':
node.set('string', _('Deliver Products'))
res['arch'] = etree.tostring(doc)
return res

You can hide a filed in a similar mannar as xml view, but you must use modify attribute like attrs.
Anyway the result let it be like this:
<field name="fieldname" modifiers={'invisible': True} />
(In my experience, if I want to take a condition to visibility, not working in fields_view_get)

Try this:
To hide the field from form view: using fields_view_get function
doc = etree.XML(res['arch'])
if show_hp_status:
for node in doc.xpath("//field[#name='status_1']"):
#use either 'invisible' or node.remove
node.set('invisible', '1')
doc.remove(node)
else:
for node in doc.xpath("//field[#name='status_2']"):
#use either 'invisible' or node.remove
node.set('invisible', '1')
doc.remove(node)
res['arch'] = etree.tostring(doc)

Related

raise exception.with_traceback(None) from new_cause ValueError: Expected singleton:

enter image description here
This my code and i don't know why this error happen.
#api.model
def update_prices_in_mitra(self):
self.ensure_one()
select_hargamitra = self.env['isd.res.partner.price_list'].search(
[('partner_id', '=', self.mitra_id.id)])
cek = []
# self.task_orderlines = [(5, 0, 0)]
for cek in select_hargamitra.price_list:
if (select_hargamitra and (len(select_hargamitra.price_list) > 0)):
for x in self.task_orderlines:
if cek.product_id.id == self.product_id.id:
x.write({'mitra_price': cek.price_amount,
'isd_mitra_status' : True})
Try this because there might be multiple record in a page i.e. tree view
#api.model
def update_prices_in_mitra(self):
for rec in self:
select_hargamitra = self.env['isd.res.partner.price_list'].search([('partner_id', '=', rec.mitra_id.id)])
cek = []
for cek in select_hargamitra.price_list:
if (select_hargamitra and (len(select_hargamitra.price_list) > 0)):
for x in rec.task_orderlines:
if cek.product_id.id == rec.product_id.id:
x.write({'mitra_price': cek.price_amount,
'isd_mitra_status' : True})

Change Many2one domain based on selection field

I want to change M2O field domain based on the user selection from selection field:
#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
but the domain not change and get the default domain from model
Change your function like this.
#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':
domain = {'search_value': [('name', 'in', partner_list)]}
return {'domain': domain}
if self.search_by == 'phone':
domain = {'search_value': [('phone', 'in', partner_list2)]}
return {'domain': domain}
Try doing this :
#api.onchange('search_by')
def _get_partner(self):
partners = self.env['customer.regist'].search([('name','!=','New')])
partner_list = []
partner_list2 = []
for rec in partners:
if rec.name :
partner_list.append(rec.name)
if rec.phone:
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
Make sure that the 'False' values are never added to the domain, since it might give invalid results

How to override fields_view_get of TransientModel in odoo 10?

I already did it and in older odoo version this way it worked!
Cant see this 'kecske' signal in the log file. No error message. If I wrote some code before super, it hasn't any effect.
Any idea? Is it the right way?
class DemoWizard(models.TransientModel):
_name = 'demo.wizard'
name = fields.Char(string='Name')
#api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
log = logging.getLogger('demo.wizard.fields_view_get()')
log.debug('kecske')
return super(DemoWizard,self).fields_view_get(view_id, view_type, toolbar, submenu)
This is from Odoo10 source. The file is found in the anonymization addon. odoo/addons/anonymization/wizard/anonymize_wizard.py. Notice the call to super() and the use of keyword arguments as apposed to positional arguments.
Other than that your code looks correct.
In your example you initialised logging using a different technique. Try initialising your logger as follows.
log = logging.getLogger(__name__)
log.info("My Log Message")
or for debug.
log.debug("My debug message")
info,debug,warning,error can be used to log different degrees of severity of log messages.
#api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
state = self.env['ir.model.fields.anonymization']._get_global_state()
step = self.env.context.get('step', 'new_window')
res = super(IrModelFieldsAnonymizeWizard, self).fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
eview = etree.fromstring(res['arch'])
placeholder = eview.xpath("group[#name='placeholder1']")
if len(placeholder):
placeholder = placeholder[0]
if step == 'new_window' and state == 'clear':
# clicked in the menu and the fields are not anonymized: warn the admin that backuping the db is very important
placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'}))
placeholder.addnext(etree.Element('newline'))
placeholder.addnext(etree.Element('label', {'string': 'Warning'}))
eview.remove(placeholder)
elif step == 'new_window' and state == 'anonymized':
# clicked in the menu and the fields are already anonymized
placeholder.addnext(etree.Element('newline'))
placeholder.addnext(etree.Element('field', {'name': 'file_import', 'required': "1"}))
placeholder.addnext(etree.Element('label', {'string': 'Anonymization file'}))
eview.remove(placeholder)
elif step == 'just_anonymized':
# we just ran the anonymization process, we need the file export field
placeholder.addnext(etree.Element('newline'))
placeholder.addnext(etree.Element('field', {'name': 'file_export'}))
# we need to remove the button:
buttons = eview.xpath("button")
for button in buttons:
eview.remove(button)
# and add a message:
placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'}))
placeholder.addnext(etree.Element('newline'))
placeholder.addnext(etree.Element('label', {'string': 'Result'}))
# remove the placeholer:
eview.remove(placeholder)
elif step == 'just_desanonymized':
# we just reversed the anonymization process, we don't need any field
# we need to remove the button
buttons = eview.xpath("button")
for button in buttons:
eview.remove(button)
# and add a message
placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'}))
placeholder.addnext(etree.Element('newline'))
placeholder.addnext(etree.Element('label', {'string': 'Result'}))
# remove the placeholer:
eview.remove(placeholder)
else:
raise UserError(_("The database anonymization is currently in an unstable state. Some fields are anonymized,"
" while some fields are not anonymized. You should try to solve this problem before trying to do anything else."))
res['arch'] = etree.tostring(eview)
return res

How to override create methode in odoo 10

i want to use same create method in odoo 10 as below means i want to convert below code in odoo 10, below code is working well for odoo 8
def create(self, cr, uid, vals, context=None):
phase_obj = self.pool.get('hr_evaluation.plan.phase')
survey_id = phase_obj.read(cr, uid, vals.get('phase_id'), fields=['survey_id'], context=context)['survey_id'][0]
if vals.get('user_id'):
user_obj = self.pool.get('res.users')
partner_id = user_obj.read(cr, uid, vals.get('user_id'), fields=['partner_id'], context=context)['partner_id'][0]
else:
partner_id = None
user_input_obj = self.pool.get('survey.user_input')
if not vals.get('deadline'):
vals['deadline'] = (datetime.now() + timedelta(days=28)).strftime(DF)
ret = user_input_obj.create(cr, uid, {'survey_id': survey_id,
'deadline': vals.get('deadline'),
'type': 'link',
'partner_id': partner_id}, context=context)
vals['request_id'] = ret
return super(hr_evaluation_interview, self).create(cr, uid, vals, context=context)
i am trying below code:
def create(self, vals):
survey_id = self.env['hr_evaluation.plan.phase'].read(vals.get('phase_id'),fields=['survey_id'])['survey_id'][0]
if vals.get('user_id'):
partner_id = self.env['res.users'].read(vals.get('user_id'), fields=['partner_id'])['partner_id'][0]
else:
partner_id = None
if not vals.get('deadline'):
vals['deadline'] = (datetime.now() + timedelta(days=28)).strftime(DF)
ret = self.env['survey.user_input'].create({'survey_id': survey_id,
'deadline': vals.get('deadline'),
'type': 'link',
'partner_id': partner_id})
vals['request_id'] = ret
return super(hr_evaluation_interview, self).create(vals)
but it is giving me error like TypeError: read() got multiple values for keyword argument 'fields' so please guide me how can i remove this error?
read method accept fields as argument and you give it two arguments.
read([fields])
Reads the requested fields for the records in self, low-level/RPC method. In Python code, prefer browse().
Parameters
fields -- list of field names to return (default is all fields)
Returns
a list of dictionaries mapping field names to their values, with one dictionary per record
Raises
AccessError -- if user has no read rights on some of the given records
Instead of calling read method it's better to call browse() method, you can read Browse() vs read() performance in Odoo 8
Your code should be:
def create(self, vals):
survey_id = self.env['hr_evaluation.plan.phase'].browse(vals.get('phase_id'))
if vals.get('user_id'):
partner_id = self.env['res.users'].browse(vals.get('user_id'))
else:
partner_id = None
if not vals.get('deadline'):
vals['deadline'] = (datetime.now() + timedelta(days=28)).strftime(DF)
ret = self.env['survey.user_input'].create({'survey_id': survey_id.id,
'deadline': vals.get('deadline'),
'type': 'link',
'partner_id': partner_id.id})
vals['request_id'] = ret.id
return super(hr_evaluation_interview, self).create(vals)

how can i use function value in Domain filter

I am getting current login user id by following function
def _get_user_name(self, cr, uid, *args):
user_obj = self.pool.get('res.users')
user_value = user_obj.browse(cr, uid, uid)
return user_value.id or False
and now i want to use its value in this field's Domain like ....
x_trainer_id = fields.Many2one('res.partner', string='Trainer',domain=[('user_id.id','=','get_user_name')])
How is it possible? I'll be very thankful....
you can do it as below:
x_trainer_id = fields.Many2one('res.partner', string='Trainer',domain=lambda self: [('id', '=', self.env.uid)])
pass domain=lambda self: [('id', '=', self.env.uid)]