Tutorial Odoo 9.0 Part 8 : Onchange & Model constraints

จาก Morange Wiki

Onchange

แก้ไขไฟล์ดังนี้

openacademy/models.py

                r.taken_seats = 0.0
            else:
                r.taken_seats = 100.0 * len(r.attendee_ids) / r.seats

    @api.onchange('seats', 'attendee_ids')
    def _verify_valid_seats(self):
        if self.seats < 0:
            return {
                'warning': {
                    'title': "Incorrect 'seats' value",
                    'message': "The number of available seats may not be negative",
                },
            }
        if self.seats < len(self.attendee_ids):
            return {
                'warning': {
                    'title': "Too many attendees",
                    'message': "Increase seats or remove excess attendees",
                },
            }

เมื่อมีการปรับเปลี่ยนค่าของ seats หรือ attendee จะทำให้ _verify_valid_seat ทำงาน

หากค่าของ seats น้อยกว่า 0 จะมีข้อความแจ้งเตือนดังภาพ
Odoo8-1.png

หากค่าของ seats น้อยกว่า attendee จะมีข้อความแจ้งเตือนดังภาพ
Odoo8-2.png


Model constraints

แก้ไขไฟล์ดังนี้

openacademy/models.py ส่วนที่ 1

# -*- coding: utf-8 -*-

from openerp import models, fields, api, exceptions

class Course(models.Model):
    _name = 'openacademy.course'

ส่วนที่ 2

                    'message': "Increase seats or remove excess attendees",
                },
            }

    @api.constrains('instructor_id', 'attendee_ids')
    def _check_instructor_not_in_attendees(self):
        for r in self:
            if r.instructor_id and r.instructor_id in r.attendee_ids:
                raise exceptions.ValidationError("A session's instructor can't be an attendee")


สร้างกฏเพื่อตรวจสอบว่า attendee กับ instructor ของ session นั้นๆ เป็นคนเดียวกันหรือไม่
หากเป็นคนเดียวกัน จะแสดงหน่าต่างแจ้งข้อผิดพลาด ดังภาพ

Odoo8-3.png