Author: ananthukrishna

How to create record adding one2many values in odoo


class sale_order(models.Model):
    _inherit = "sale.order"
    
    #By default load the terms and conditions configured in the master T&C configuration
    @api.model
    def default_get(self,vals):
        terms = []
        terms_obj = self.env['so.terms.config']
        termsids = terms_obj.search([])
        for rec in termsids:
            terms.append((0, 0, {'name':rec.name,'description' : rec.description}))
        res = super(sale_order, self).default_get(vals)      
        res.update({'terms': terms})
        return res

    terms = fields.One2many('sale.order.terms.conditions','order_id',string='Terms & Conditions',copy=True)

How to create sequence Code in odoo


.py file

class res_partner(osv.osv):
    _inherit = 'res.partner'
    _description = "Customers"

    _columns = {
        'code': fields.char('Student ID',size=64, readonly=True),
    }
    
    _sql_constraints = [
    ('unique_code', 'unique(code)', 'Number of Student must be unique!'), 
    ]  
    
    # Override the customer create fuction for genarate Students Unique number 
    def create(self, cr, uid, vals, context=None):
        if vals.get('is_company') == True:
                vals['code']=self.pool.get('ir.sequence').get(cr, uid, 'res.partner.student')
        return super(res_partner,self).create(cr, uid, vals, context)   

.xml file

<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data noupdate="1">

    <!-- Sequence types for customer codes -->

    <record id="seq_type_res_student" model="ir.sequence.type">
        <field name="name">Student Code</field>
        <field name="code">res.partner.student</field>
    </record>

    <!-- Sequences for customer codes -->

    <record id="seq_res_student" model="ir.sequence">
        <field name="name">Student Code</field>
        <field name="code">res.partner.student</field>
        <field name="prefix"></field>
        <field name="padding">3</field>
    </record>
      
    </data>
</openerp>

How to override form widgets odoo javascript


JS:

// path_to_your_module/static/src/js/form_widgets.js
odoo.define('your_module.form_widgets', function (require) {
    "use strict";

    var core = require('web.core');
    var form_common = require('web.form_common');
    var FieldChar = core.form_widget_registry.get('char');

    FieldChar.include({
        // this is will be work for all FieldChar in the system
        template: 'MyChar', // my template for char fields
        // we can create here any logic for render
        //render_value: function() {
        //}
    });
    // this is widget for unique CharField
    var MyModuleFieldChar = FieldChar.extend({
        template: 'MyUniqueChar' // my custom template for unique char field
    });
    // register unique widget, because Odoo does not know anything about it
    core.form_widget_registry.add('my_unique_char', MyModuleFieldChar);

});

Templates for qWeb:

<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
<!-- path_to_your_module/static/src/xml/form_widgets.xml -->
<t t-name="MyChar">
    <!-- for example I just added new <span> to all FieldChar -->
    <span>my_val</span>
    <!-- this is original content for CharField from path_to_odoo/addons/web/static/src/xml/base.xml -->
    <span t-att-class="'oe_form_field '+widget.widget_class" t-att-style="widget.node.attrs.style">
        <t t-if="!widget.get('effective_readonly')">
            <input t-att-type="widget.password ? 'password' : 'text'"
                t-att-barcode_events="widget.options.barcode_events"
                t-att-id="widget.id_for_label"
                t-att-tabindex="widget.node.attrs.tabindex"
                t-att-autofocus="widget.node.attrs.autofocus"
                t-att-placeholder="widget.node.attrs.placeholder"
                t-att-maxlength="widget.field.size"
            /><img class="oe_field_translate oe_input_icon" t-if="widget.field.translate" t-att-src='_s + "/web/static/src/img/icons/terp-translate.png"' width="16" height="16" border="0"/>
        </t>
        <t t-if="widget.get('effective_readonly')">
            <span class="oe_form_char_content"></span>
        </t>
    </span>
</t>
<!-- This is example template for my unique field -->
<t t-name="MyUniqueChar">
    <span>unique_char</span>
</t>

</templates>

Second step – include our static files.
Create new view which will be add assets:

<?xml version="1.0" encoding="utf-8"?>
<!-- path_to_your_module/views/assets.xml -->
<openerp>
    <data>
        <template id="assets_backend" name="mail assets" inherit_id="web.assets_backend">
            <xpath expr="." position="inside">
                <script type="text/javascript" src="/your_module/static/src/js/form_widgets.js"></script>
            </xpath>
        </template>
    </data>
</openerp>

In openerp.py of your module add next sections:

'data': [
    'views/assets.xml',
    # other files
],
'qweb': [
    'static/src/xml/*.xml',
],

After this will be work our FieldChar for all CHAR fields in the system. If we need to use my_unique_char we need just add attribute widget to field of our from like this:

<field name="name" widget="my_unique_char"/>

how to call python function from Javascript odoo


Python class:

Define the class and its method:


class message_of_the_day(osv.osv):
  _name = "message_of_the_day"

  def my_method(self, cr, uid, context=None):
   return {"hello": "world")}

Javascript file: Define the javascript file and write down the function-

openerp.module_name = function(instance)
{
 instance.module_name.MyClass = instance.web.Class.extend(
 {
   hi_start: function()
   {
     var self = this;

  #initialize the object in js file

var model = new instance.web.Model("message_of_the_day");

  #call the method of the above class
     model.call("my_method", [], {context: new instance.web.CompoundContext()}).then(function(result)
     {
       console.log("hello world, I am working");
     });
 },
});
var my_object = new instance.module_name.MyClass();
my_object.hi_start();
}

Print qwebreport using button – odoo


def ep_print_soap(self, cr, uid, ids, context=None):
        '''
        This function prints the Consultation Form
        '''
        assert len(ids) == 1, 'This option should only be used for a single id at a time'
        return self.pool['report'].get_action(cr, uid, ids, 'ep_headstart_sales.report_soapform', context=context)
<button name="ep_print_soap" string="Print" type="object" class="oe_highlight"/>

odoo javascript formView include


openerp.test = function(instance) {
     var _t = instance.web._t,
        _lt = instance.web._lt;
     var Qweb = instance.web.qweb;

    
     instance.web.FormView.include({
        
        init : function() {
            var self = this;
            this._super.apply(this, arguments);
        },
        start : function(){
            this._super.apply(this, arguments);
            var self=this;
            self.get_selected_ids();

        },

        get_selected_ids: function ()
	   {
	       var ids =[];
	       this.$el.find('#o_field_input_10').each(function () {
					ids.push(parseInt($(this).val()));
					console.log(ids);
	       });
	       return ids;
	   },



    });
};

Odoo custom form field widget – javascript


Custom widget Javasript

openerp.mymodule = function(instance, local) {
    instance.ImageDisplayer = instance.web.form.AbstractField.extend({
        template: "ImageDisplayer",
        init: function (view, code) {
            this._super(view, code);
        },
        // The key part:
        render_value: function() {
            this.$el[0].src = this.get("value");
        }
    });
    instance.web.form.widgets.add('ImageDisplayer', 'instance.ImageDisplayer');
}

Template

<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
    <t t-name="ImageDisplayer">
        <img />
    </t>
</templates>

How to get a value of model field using javascript – odoo


var Users = new openerp.Model('res.users');
Users.query(['name', 'login', 'user_email', 'signature'])
     .filter([['active', '=', true], ['company_id', '=', main_company]])
     .limit(15)
     .all().then(function (users) {
    // do work with users records, you can access only fields said in query
     for(i in users){
         console.log(i.name)
     }
 });

how many2many defined for custom module odoo


.py file

class notebook(osv.osv):
_name = "notebook"
_columns = {
    'title' : fields.char('Title', size=30, required=True),
    'tag_ids': fields.many2many(
                'hello',
                'notebook_hello_rel',
                'notebook_id',
                'hello_id',
                string="Tags"
                            ),
}

class hello(osv.osv):
_name = 'hello'
_columns = {
        'name':fields.char('Name',size=30),
        'note_ids': fields.many2many(
                            'notebook',
                            'notebook_hello_rel',
                            'hello_id',
                            'notebook_id',
                            string="Notebooks"
                                    ),
                } 

.xml file

many2many widget (default)
<field name="tag_ids" options="{'no_create': True}"/>

many2many_tags widget
<field name="tag_ids" widget="many2many_tags" options="{'no_create_edit': True}"/>

many2many_checkboxes widget
<field name="tag_ids" widget="many2many_checkboxes"/>

many2many_kanban widget

<field name="tag_ids" widget="many2many_kanban">
    <kanban>
        <field name="name"/>
        <templates>
            <t t-name="kanban-box">
                <field name="name"/>
            </t>
        </templates>
    </kanban>
</field>

x2many_counter widget
<field name="tag_ids" widget="x2many_counter" string="things"/>

many2many_binary widget
<field name="tag_ids" widget="many2many_binary" string="Attach a file"/>