Javaziez

How to Create Many 2 Many in Custom Module Odoo?

Pada artikel ini, akan dijelaskan cara membuat data yang merupakan relasi many2many antar dua tabel. Berikut tampilan yang akan dibuat.

Customer -> customer products <- Product

Pada halaman detail customer, ada tab yang menampilkan data Customer Products. Berikut langkah-angkahnya.

1. Dari artikel sebelumnya tentang create custom module (customer model), sekarang kita akan membuat model product dan view nya.

2. Tambah menu Product di file views/views.xml.

<record id="action_product_tree" model="ir.actions.act_window">
      <field name="name">Product</field>
      <field name="res_model">customer.product</field>
      <field name="view_mode">tree,form</field>
      <field name="help" type="html">
          <p class="o_view_nocontent_smiling_face">
              Create Product Record
          </p>
      </field>
</record>

<!--Menu Product -->
<menuitem id="product_menu"
     name="Product"
     parent="registration.customer_menu_root"
     action="action_product_tree"/>

3. Buat field relasi antara class customer dan class baru, yaitu CustomerProductRegistration class di file models/customer.py

customer_product_id = fields.One2many('customer.product.registration', 'customer_id', string="Product", ondelete='no action')

class CustomerProductRegistration(models.Model):
      _name = 'customer.product.registration'

      product_id = fields.Many2one('customer.product', string="Product", required=True)
      product_name = fields.Char(related='product_id.name', string="Product Name")
      stock = fields.Char(string="Stock")
      tonase = fields.Char(string="Tonase")
      customer_id = fields.Many2one('customer.customer', string="Customer Name")

4. Tambahkan kolom relasi di product class. (customer_id, customer_product_id)

customer_id = fields.Many2one('customer.customer', string="Customer Name", required=True)
customer_product_id = fields.One2many('customer.product.registration', 'product_id', string="Customer Name", ondelete='no action')

5. Tambahkan tab form customer product di customer views (file views/customer_views.xml).

<notebook>
   <page string="Customer Products">
      <field name="customer_product_id">
          <tree editable="bottom">
              <field name="product_id"/>
              <field name="stock"/>
              <field name="tonase"/>
              <field name="customer_id" invisible="1"/>
          </tree>
      </field>
   </page>
</notebook>

6. Tambahkan akses ke class CustomerProductRegistration di file security/ir.model.access.csv.

access_customer_product_registration,customer.product.registration,model_customer_product_registration,base.group_user,1,1,1,1

7. Selanjutnya, restart Odoo docker lalu upgrade module customnya. Selesai

Untuk lebih jelasnya, silahkan kunjungi videonya di channel kami.

Exit mobile version