Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 16120

how to establish the connections between controller.py, JavaScript (JS), and XML templates in Odoo 17?

$
0
0

Im trying to create basic attendance form, where changing class division will populate the students in the below table, and next column will be selection for present/absent and submitting.

Controller

im trying to redirect to my template using the controller method

class StudentAttendanceController(http.Controller):

@http.route('/attendance_form', type='http', auth="public", website=True)def attendance_form(self, **kw):    return request.render("aspire_student_attendance.attendance_form_template", {'today': fields.Date.today()})@http.route('/submit_attendance', type='json', auth="user")def submit_attendance(self, **kw):    class_division_id = kw.get('class_division_id')    date = kw.get('date')    student_attendances = kw.get('student_attendances')  # Expected to be a list of dicts with student_id and attendance_status    Attendance = request.env['student.attendance']    AttendanceLine = request.env['student.attendance.line']    faculty_id = request.env.user.id  # Current user's ID    attendance_record = Attendance.create({'date': date,'class_division_id': class_division_id,        # 'faculty_id': user_name,  # Add the teacher's name to the attendance record'faculty_id': faculty_id,  # Link the teacher (current user) to the attendance record'attendance_status': 'draft',  # Initial state of the attendance record    })    for student_attendance in student_attendances:        AttendanceLine.create({'attendance_id': attendance_record.id,'student_id': student_attendance['student_id'],'attendance_status': student_attendance['attendance_status'],        })    return {'success': True, 'message': 'Attendance successfully recorded'}@http.route('/get_students', type='json', auth='user')def get_students(self, **kwargs):    students = request.env['school.class.division'].browse([2]).student_ids    student_data = [{'student_id': student.id, 'student_name': student.name} for student in students]    print('student data', student_data)    return student_data

main.js

`

odoo.define('aspire_student_attendance.attendance_form', ['web.ajax'], function (require) {"use strict";        var ajax = require('web.ajax');        const core = require('web.core');        var _t = core._t;        $(document).ready(function () {            $('select[name="class_division_id"]').on('change', function () {                const classId = $(this).val();                if (classId) {                    this.rpc({route: "/get_students",                              params: {class_division_id: classId}}).   then(function (response) {                            const studentList = $('#students_list');                            studentList.empty();                            $.each(response, function (index, student) {                                const studentEntry = $('<div>')                                    .addClass('student_attendance_input')                                    .text(student.name)                                    .data('student-id', student.id);                                $('<input>', {                                    type: 'checkbox',                                    name: `attendance[${student.id}]`,                                    value: 'present'                                }).appendTo(studentEntry);                                studentList.append(studentEntry);                            });                        }).catch(function (error) {                            console.error("Error fetching students:", error);                        });                } else {                    $('#students_list').empty();                }            });            $('button[name="submit_attendance"]').on('click', function (e) {                e.preventDefault();                const classId = $('select[name="class_division_id"]').val();                const date = $('input[name="date"]').val();                const studentAttendances = [];                $('.student_attendance_input input[type="checkbox"]').each(function () {                    const studentId = $(this).closest('.student_attendance_input').data('student-id');                    const attendanceStatus = $(this).is(':checked') ? 'present' : 'absent';                    studentAttendances.push({                        student_id: studentId,                        attendance_status: attendanceStatus,                    });                });                if (!classId || !date || studentAttendances.length === 0) {                    alert("Please select a class, enter a date, and mark student attendance.");                    return;                }                ajax.rpc('/submit_attendance', {                    class_division_id: classId,                    date: date,                    student_attendances: studentAttendances,                }).then(function (result) {                    if (result.success) {                        alert(result.message);                        $('#students_list').empty();                        $('select[name="class_division_id"]').val('');                        $('input[name="date"]').val('');                    }                }).catch(function (error) {                    console.error("Error submitting attendance:", error);                });            });        });    });`

Xml template

<template id="attendance_form_template" name="Student Attendance Form"><t t-call="website.layout"><div class="container"><h1>Student Attendance</h1><div class="attendance-header"><h2>Status: <span t-esc="attendance_status"/></h2></div><div class="faculty-info"><span>Faculty: <span t-esc="faculty_name"/></span><span>Date: <input type="date" id="date" name="date" class="form-control" t-att-value="today" readonly="readonly"/></span><span>Class: <select id="class_select" name="class_division_id" class="form-control" required="required"><t t-foreach="request.env['school.class.division'].sudo().search([])" t-as="class"><option t-att-value="class.id"><t t-esc="class.name"/></option></t></select></span></div><table class="table"><thead><tr><th>Student</th><th>Selection</th></tr></thead><tbody id="students_list"><!-- Students will be loaded here via AJAX --></tbody></table><button name="submit_button" type="submit" class="btn btn-primary">Submit Attendance</button></div></t></template>

Manifest.py

    {'name': 'School Management','version': '17.0.1.0.0','category': 'School Management','summary': """School Management Extended""",'author': 'AAAA','company': 'AAAA','website': "",'depends': ['base', 'web', 'website'],'data': ['security/ir.model.access.csv','views/student_attendance_views.xml',        # 'views/website_menu.xml',        # 'views/assets.xml','views/student_attendance_form.xml','views/home.xml',    ],'assets': {'web.assets_frontend': ['aspire_student_attendance/static/src/student_attendance_form/**/*',        ],    },'installable': True,'auto_install': False,'application': True,'license': 'AGPL-3',}

Viewing all articles
Browse latest Browse all 16120

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>