2

I want to set default value in many2one field. But i want to set it by python code in server action at on-creation. Problem is that, I don't know what are the rules and regulations of writing python code in server action. Is there any way to to set default value of Many2one field in server action. For example: Same work is there through customized code Set default value of field depends on other field in odoo

I'll be very thankful ...

Community
  • 1
  • 1
M Tahir Noor
  • 443
  • 2
  • 10
  • 31

1 Answers1

1

You can use an automatic action for this requirement. Just create one at Settings/Technical/Automation/Automated Actions. Give it a name, the correct model you want to run it on and ofcourse set "When to run" to "On Creation".

On the second tab add a new server action. Following a simple code snippet for the server action (it's for sale.order and you need an ir.config_parameter with the given external id):

object.write({'client_order_ref': 'YourRef'})
if 'A' in object.partner_id.name:
    object.write({'note': 'AAAAAAAAAA'})
else:
    object.write({'note': env.ref('mymodule.mycool_ir_config_parameter').value})

The example is written for Odoo V8+.

CZoellner
  • 13,553
  • 3
  • 25
  • 38
  • Sir I am writing this code `if object.debit==0: res=self.pool.get('account.analytic.account').search(cr, uid, [('name','=','Internal')], context=context) object.write({'account_analytic_id': res})` in server action but it is doing nothing.. please help me about it... – M Tahir Noor Aug 09 '16 at 10:11
  • Sir you are setting char field value... can you please tell me how to set `many2one` field value.. pleaseeee... – M Tahir Noor Aug 09 '16 at 11:32
  • You can do searches or use `env.ref()` to get other records. After that just set your many2one field with an record ID. For example (i know it isn't the best example): `object.write({'partner_id': env['res.partner'].search([], limit=1).id})` will set the first partner in database as default partner in `sale.order` creation. – CZoellner Aug 09 '16 at 13:37
  • Thanks sir.this code is now working well for me.. `res = self.pool.get('account.analytic.account').search(cr, uid, [('name','=','Internal')], context=context) object.write({'analytic_account_id': res[0]})` Thanks ... you are the best.... – M Tahir Noor Aug 09 '16 at 16:19
  • Sir can you please tell me how to compare `current login user id` there in python code of `server action` – M Tahir Noor Aug 10 '16 at 16:38
  • if you're on Odoo V8+ you can use `env.user.id` to get the current user ID – CZoellner Aug 10 '16 at 17:04
  • Sir can you please tell me how to get current user name in qweb report??? – M Tahir Noor Aug 18 '16 at 18:24
  • That has nothing to do with this question/answer – CZoellner Aug 18 '16 at 19:14