1

When click on Add an Item in tree view, I want in new row copy value from last inserted row.

Eg. if field name = 'Text' in new row I need in field name string 'Text'

Any simple solution?

user_odoo
  • 2,284
  • 34
  • 55

1 Answers1

2

If you want to load default value from a database then follow this method.

You can achieve it by overriding default_get method and in that, you need to write your logic.

@api.model
def default_get(self,fields):
    res = super(class_name, self).default_get(fields)
    last_rec = self.search([], order='id desc', limit=1)
    if last_rec:
        res.update({'your_field_name':last_rec.field_value})
    return res

While you click on add an item it will fill the new record with its default value and in default value we have written last record's value it it's there.

If you want to load default value from list view (last added value in a list) then it's a bit tricky work, for that you can do something like as follow.

Add one field in the parent form.

last_added_value = fields.Char("Last Added Value")

Create onchange method for that field.

@api.onchange('field_name')
def onchange_fieldname(self):
    # there must be many2one field of parent model, use it here.
    self.parent_model_field.last_added_value = self.field_name

And in xml field, you need to write like this.

<field name="one2many_field" context="{'default_field_name' : parent.last_added_value}">
    <tree string="Title" editable="bottom">
        <field name="field_name"/>
    </tree>
</field>

You also need to write default_get method.

@api.model
def default_get(self,fields):
    res = super(class_name, self).default_get(fields)
    last_rec = self.search([('parent_field_id','=',self.parent_field_id.id)], order='id desc', limit=1)
    if last_rec:
        res.update({'your_field_name':last_rec.field_value})
    return res
KbiR
  • 4,047
  • 6
  • 37
  • 103
  • Your example return last value from database, Is it possible get last row added on tree view but not saved in database? – Pointer Jul 21 '17 at 06:48
  • Not sure about that, it may help you https://stackoverflow.com/questions/41185336/set-default-value-while-creating-record-from-one2many-field-odoo – Emipro Technologies Pvt. Ltd. Jul 21 '17 at 06:54
  • Technologies Pvt. Ltd After open new form and in tree view add new row, after click on add an item new row is empty. After save first row in database your example return last value from database. For example: In database I have value 1, in tree view I'm add 3 new row (2,3,4) after click on Add an Item I need value 4 (not saved in database but visible in tree view). – Pointer Jul 21 '17 at 07:00
  • Tnx for help, but your example don't work for me please see link http://imgur.com/a/t6trs – Pointer Jul 21 '17 at 08:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/149797/discussion-between-emipro-technologies-pvt-ltd-and-pointer). – Emipro Technologies Pvt. Ltd. Jul 21 '17 at 10:00