Reputation: 177
I have this calendar that is made with Javascript.
When you click in "Libre", a view opens, where you can create a reserve. I want the reservation line as default and look something like this. In this case I did it manually, and I want it to appear automatically. I know I need an on @api.onchange
function.
The roomid
field ("Room" in the image) has the ID of the room that I need to add in reservation.line. I get this from .js
I have something like this in my code and it's getting exactly the room I want, but I don't know how to make it appear automatically.
class HotelReservation(models.Model):
_name = "hotel.reservation"
room_id = fields.Many2one("hotel.room", string="Room", required=True)
roomid= fields.Integer(related='room_id.id', string="Room")
reservation_line = fields.One2many(
"hotel.reservation.line",
"line_id",
string="Reservation Line",
help="Hotel room reservation details.",
readonly=True,
states={"draft": [("readonly", False)]},
)
@api.onchange('roomid')
def onchange_reservation_line(self):
if self.roomid:
room = self.env['hotel.room'].search([('id' ,'=', self.roomid)])
# Some return here?
Upvotes: 1
Views: 495
Reputation: 26708
You can read in the write function documentation that the expected value of a One2many or Many2many relational field is a list of Command that manipulates the relation the implement. There are a total of 7 commands: create(), update(), delete(), unlink(), link(), clear(), and set().
roomid
is related to room_id
so you can use it in onchange function and avoid calling the search method to get the room record.
Example:
@api.onchange('room_id')
def onchange_reservation_line(self):
if self.room_id:
self.reservation_line = [
Command.clear(),
Command.create({
'field_name': field_value,
...
}),
]
Upvotes: 1