Skip to content
Home » Odoo Portal Form View Tutorial: Build Student Profile Form

Odoo Portal Form View Tutorial: Build Student Profile Form

  • Odoo

Welcome to this comprehensive tutorial on creating an Odoo portal form view for building a student profile registration form. In this guide, we will explore how to design an interactive website portal for Odoo web development while focusing on the key technique of constructing an efficient form view. You will learn to handle Odoo controllers, customize breadcrumb navigation, and design an intuitive XML template for a registration form. By the end of this tutorial, you will have a solid understanding of how to implement and extend a form view within your Odoo website portal—all in an active, step‐by‐step manner.

In this article, we emphasize the concept of an “Odoo portal form view” and its synonyms such as “Odoo web form,” “portal customization form,” and “student registration view.” We will integrate these keyphrases throughout the discussion. Moreover, the topic is laid out clearly from the beginning to make it easy to grasp the goal and the practical applications of the provided code. You can also check out further details on Odoo development in the Odoo Documentation.


Table of Contents

Understanding the Odoo Website Portal and Form Views

Before we dive into the code, it is crucial to understand how Odoo’s website portal works and why form views are an essential part of its design. Odoo provides a flexible and powerful framework that allows developers to create custom modules and extend the capabilities of the platform. In the context of a portal form view, you are building a user interface function where end users—such as students registering at a school—can submit information.

Besides the user interface, the back-end logic is equally important. We use an Odoo controller to render the page template and serve data from the Odoo models. Also, template inheritance and XML code allow you to create dynamic and customizable navigational elements like breadcrumbs and forms. Transitioning seamlessly between the code components requires an understanding of both Python and XML code structures.

As we progress, we will see the interplay between the Python code that handles HTTP requests and the XML code that builds the view. Throughout this tutorial, you will notice the active steps taken to retrieve and render school profiles, handle form submission, and build dynamic content. By strictly following the active voice and adding transition words, we ensure that the tutorial flows clearly for beginners and advanced users alike.


The Odoo Controller Code for Portal Form View

In Odoo, a controller connects the web interface with the back-end logic. The following Python code snippet defines a controller that is responsible for rendering the new student registration form. This code forms the backbone of our Odoo portal form view.

Python Controller (Odoo Portal)

from odoo import http
from odoo.http import request

class WeblearnsPortal(http.Controller):

    @http.route(["/new/student"], type="http", auth="user", website=True)
    def registerStudentProfile(self, **kw):
        school_list = request.env['school.profile'].search([])
        return request.render("wb_portal.new_student_form_view_portal", {
            'schools': school_list,
            'page_name': "register_student"
        })

Explanation

  • Importing Odoo Modules:
    We begin by importing the http module from Odoo, which helps in handling web requests. The request object is used to interact with the Odoo environment.
  • Controller Definition:
    The WeblearnsPortal class inherits from http.Controller, which makes it possible to define routes and render templates.
  • Routing with @http.route:
    The method registerStudentProfile is decorated with the @http.route decorator. This decorator maps the URL /new/student to our method. We also set type="http", auth="user", and website=True to ensure that this route is accessible via the website and only to authenticated users.
  • Fetching Data:
    Inside the method, the search([]) function retrieves all records of the school.profile model. This data populates the dropdown list in the student registration form.
  • Rendering the Template:
    Finally, request.render renders the XML template named "wb_portal.new_student_form_view_portal". The dictionary passed along contains key variables such as a list of schools and the page name. This modular approach separates the application logic from the presentation layer.

This controller is a critical component in generating the Odoo portal form view. Next, we will examine how the breadcrumb navigation element is built using XML templates.


Building the Breadcrumb Navigation with XML

Breadcrumbs play an essential role in enhancing user navigation in your portal. They let users know where they are and how to move between sections of the website. The following XML code snippet shows how you can build breadcrumb navigation for different portal pages.

Breadcrumbs Template (XML)

<template id="portal_breadcrumbs" inherit_id="portal.portal_breadcrumbs">
    <xpath expr="//ol[hasclass('o_portal_submenu')]" position="inside">
        <li t-if="page_name == 'students_list_view'" class="breadcrumb-item">Students</li>
        <li t-if="page_name == 'register_student'" class="breadcrumb-item">Register Student</li>
        <li t-if="page_name == 'students_form_view'" class="breadcrumb-item">
            <a href="/my/students">Students</a> /
            <span t-out="student.name" />
        </li>
    </xpath>
</template>

Explanation

  • Template Inheritance:
    The <template> tag inherits from a base template (portal.portal_breadcrumbs). This technique ensures consistency throughout all portal pages. The inherited template can be extended without duplicating code.
  • Dynamic Breadcrumb Items:
    Using conditional statements like t-if, the template displays different breadcrumb items based on the current page. For instance, if page_name equals "register_student", it shows the breadcrumb item “Register Student.”
  • Dynamic Data Rendering:
    The <span t-out="student.name" /> dynamically inserts the student’s name into the breadcrumb when necessary. This active insertion of data makes the navigation contextual and user-friendly.

These XML snippets help establish a user-centric design, which is critical when crafting your Odoo portal form view. Next, you will see the XML template that builds the complete student registration form.


Creating the Student Registration Form Template

The form template is the heart of this tutorial. It allows users to input their information and register as a new student. The XML code below defines the structure and design of this form.

Student Registration Form Template (XML)

<template id="new_student_form_view_portal">
    <t t-call="portal.portal_layout">
        <t t-call="portal.portal_table">
            <form>
                <div class="form-group row">
                    <label class="col-sm-2 col-form-label" for="name">Name</label>
                    <div class="col-sm-10">
                        <input type="char" name="name" id="name" class="form-control" placeholder="Enter Student Name"/>
                    </div>
                </div>

                <div class="form-group row">
                    <label class="col-sm-2 col-form-label" for="school">School</label>
                    <div class="col-sm-10">
                        <select name="school" id="school" class="form-control">
                            <option>Selection School</option>
                            <t t-foreach="schools" t-as="school">
                                <option t-att-value="school.id">
                                    <t t-out="school.name" />
                                </option>
                            </t>
                        </select>
                    </div>
                </div>

                <div class="form-group row">
                    <div class="col-sm-10">
                        <button type="submit" class="btn btn-primary">Create Student Profile</button>
                    </div>
                </div>
            </form>
        </t>
    </t>
</template>

Detailed Explanation

In this XML template, we actively build a dynamic form view that leverages Odoo’s powerful templating engine:

  • Template Inheritance:
    The template uses <t t-call="portal.portal_layout"> which ensures that your form inherits the layout and styling from the main portal. Consequently, it maintains a consistent look and feel across pages.
  • Table Layout Integration:
    By calling <t t-call="portal.portal_table">, we integrate the form into the table layout that Odoo uses for portal pages. This provides a grid-like structure that aligns with the overall design.
  • Form Elements:
    The form is divided into several <div> blocks marked with "form-group row" classes, ensuring a responsive design with Bootstrap. Each segment (for example, the input for the student name and the selection dropdown for schools) is clearly defined.
  • The <input> element for the student’s name includes a placeholder and maintains clarity.
  • The <select> tag iterates over the schools variable (populated by the controller) to create a dropdown list of available schools dynamically.
  • Submission Button:
    A button, styled with btn btn-primary, actively triggers the form submission. This button is crucial for creating the student profile record once the user has filled in the details.

Transitional words like “next” and “finally” ensure a flowing experience for the reader. In the next section, we will explore how to extend your Odoo portal form view with additional functionality.


Extending and Enhancing the Odoo Portal Form View

Once you have built the basic student registration form, you may want to extend its functionality to suit your needs. In this section, we discuss active ways to enhance your form and customize it further.

Adding Validation and Custom Fields

You may decide to add extra validations and custom fields. For example:

  • Custom Field Addition:
    You can add a field for the student’s email address or phone number by simply inserting an additional <div> block in the XML template. Use familiar form-control classes to ensure consistency.
  • Validation Using JavaScript:
    You can integrate JavaScript to validate the form before submission. This activity ensures that the user inputs valid, required data. Along with that, use transition words such as “furthermore” or “additionally” to guide the reader through the enhancement process.

Example: Adding an Email Field

Below is an example of how to add an email input field to your student registration form:

<div class="form-group row">
    <label class="col-sm-2 col-form-label" for="email">Email</label>
    <div class="col-sm-10">
        <input type="email" name="email" id="email" class="form-control" placeholder="Enter Student Email" required/>
    </div>
</div>

Explanation

  • The email field actively employs the required attribute to enforce input validation.
  • The input type is set to email to activate the browser’s built-in email validation.
  • The code block remains consistent with the previously defined fields for a streamlined appearance.

Adding Client-Side Scripting

To further enhance the user experience, implement client-side scripting with JavaScript. The following snippet demonstrates how to validate input fields before form submission:

<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.querySelector('form');
        form.addEventListener('submit', function (e) {
            const nameField = document.getElementById('name');
            const emailField = document.getElementById('email');
            if (!nameField.value || !emailField.value) {
                alert('Please fill in all required fields.');
                e.preventDefault();
            }
        });
    });
</script>

Explanation

  • Event Listener:
    The script adds an event listener for the DOMContentLoaded event to ensure that the DOM is fully loaded before executing any scripts.
  • Validation Function:
    The function validates both the name and email fields. If either is empty, it prevents form submission and alerts the user.
  • Active Transitions:
    Moreover, the script uses clear, transition-based language to walk through the validations step by step.

By incorporating these enhancements, you actively improve your Odoo website portal form view, making it more robust and user-friendly.


Testing and Debugging Your Odoo Form View

It is crucial to test every part of your code to ensure that your portal form is both functional and user-friendly. Follow these steps to test and debug your Odoo portal form view:

Step 1: Checking the Controller Functionality

Ensure that your Python controller correctly retrieves data from your Odoo model. You can test this by:

  • Verifying that the URL /new/student correctly navigates to the form.
  • Checking if the list of schools appears in the dropdown.

Step 2: Validating the XML Template

Next, inspect the XML template by:

  • Using Odoo’s developer mode to inspect the rendered page.
  • Confirming that the breadcrumb navigation displays the correct items based on the page context.

Step 3: Browser Testing for Form Submission

When testing in a browser:

  • Actively submit the form with valid and invalid inputs.
  • Observe how the JavaScript validation works.
  • Check the console for any errors that might appear in the network requests or during the DOM rendering.

Step 4: Debugging and Logs

If you run into issues:

  • Use logger functionality in Python to log messages.
  • Check the Odoo logs for any warnings or errors.
  • Utilize browser developer tools to inspect network activity and console logs.

By following these active testing and debugging steps, you ensure that the Odoo portal form view operates seamlessly and responds to user interactions.


Deployment and Upgrading Your Module

After building and testing your Odoo web development portal form view, the next step is to deploy the module to production.

Preparing Your Module for Deployment

Before deploying, review your code actively to ensure that:

  • All files are updated and saved.
  • Your module’s manifest file includes dependencies.
  • Necessary assets (CSS, JavaScript, and XML files) are bundled correctly.

Upgrading the Module in Odoo

Once ready, you can upgrade the module within Odoo using the following command in the terminal:

./odoo-bin -u your_module_name -d your_database

Explanation

  • Upgrade Command:
    The command actively upgrades your custom module by running it against your chosen database.
  • Clear Cache:
    Thoughtfully clear your browser cache after upgrading the module to ensure that the latest changes are reflected.
  • Restart the Odoo Service:
    In some cases, you might need to restart the Odoo service to reinitialize the configurations.

For additional resources on deploying Odoo modules and best practices in Odoo development, visit the Odoo Developer Documentation.

Through these deployment steps, you actively transfer your development environment code to a production environment, ensuring that users can easily access and use the new student registration form.


Customizing the User Interface with Bootstrap and CSS

To make sure that your portal form view is visually appealing, consider customizing its look with Bootstrap and additional CSS styling.

Customizing Form Elements

You can override existing styles by including a custom CSS file. For example:

/* custom_portal_styles.css */
.form-group label {
    font-weight: bold;
    color: #333;
}
.form-control {
    border-radius: 0.25rem;
    border: 1px solid #ccc;
}
.btn-primary {
    background-color: #007bff;
    border-color: #007bff;
}

Explanation

  • Styling Labels and Inputs:
    The CSS code actively enhances the readability and consistency of labels and input fields found in the Odoo portal form view.
  • Enhancing the Button Appearance:
    The styles ensure that the primary button has a modern look while adhering to the design language of Bootstrap.

Integrating Custom CSS in Your Template

You can include the custom CSS in your form template by adding the following line inside the <head> section of your layout template:

<link rel="stylesheet" href="/your_module/static/src/css/custom_portal_styles.css"/>

This practice ensures your changes are applied consistently across the form view and other portal pages.


Integrating Additional Features: Extending Functionality

Beyond the basics, you might want to add extra features to your portal form view. These enhancements could include:

1. Dynamic Field Updates with Ajax

Ajax enables you to update parts of the form view without reloading the entire page. This functionality improves user experience.

Example: Updating Dropdown Options Dynamically

<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
        const schoolSelect = document.getElementById('school');
        schoolSelect.addEventListener('change', function () {
            // Simulate an Ajax request to dynamically update another field
            console.log('Selected school ID:', schoolSelect.value);
            // Here you can add further functionality to update additional form fields based on school selection.
        });
    });
</script>

This technique not only makes your form more interactive but also leads to enhanced user satisfaction. Transitioning to this modern technique adds value to your Odoo web portal form view.

2. Multi-step Registration Form

Instead of a simple one-page form, you can convert your registration process into a multi-step form. Doing so will break down the registration process into smaller, manageable sections. For instance:

  • Step 1: Enter overall profile details (name, email, etc.).
  • Step 2: Select the school and related programs.
  • Step 3: Confirm and submit the details.

By actively structuring your form into multiple steps, you improve usability and reduce form fatigue. You can leverage JavaScript frameworks such as jQuery or even vanilla JavaScript to handle these transitions.


Practical Example: Enhancing the Controller to Support Multi-Step Forms

To further enhance the user experience, modify the Python controller to dynamically handle multi-step form submissions. Although this example is conceptual, it demonstrates an active way of approach.

Sample Enhanced Controller Code

from odoo import http
from odoo.http import request

class WeblearnsPortal(http.Controller):

    @http.route(["/student/step1"], type="http", auth="user", website=True)
    def studentStepOne(self, **kw):
        # Active retrieval of school list for step one
        school_list = request.env['school.profile'].search([])
        return request.render("wb_portal.student_step_one", {
            'schools': school_list,
            'page_name': "register_student_step1"
        })

    @http.route(["/student/step2"], type="http", auth="user", website=True, methods=['POST'])
    def studentStepTwo(self, **kw):
        # You can process and store step one data here and then render step two
        return request.render("wb_portal.student_step_two", {
            'page_name': "register_student_step2"
        })

Explanation

  • Multi-step Routes:
    Two distinct routes are defined for different steps in the registration process (e.g., /student/step1 and /student/step2).
  • Handling Data Transitions:
    Each step actively handles data retrieval or submission, ensuring that the form progresses logically and smoothly.

By segmenting the registration process, you engage users actively and make complex forms easier to complete.


Performance Optimization and Best Practices

To ensure that your Odoo portal form view performs efficiently in a production environment, consider adopting the following best practices:

Code Optimization

  • Minimize Data Queries:
    Actively limit the data retrieved by your controller. Use domain filters in your search([]) query if necessary.
  • Cache Often Used Data:
    Utilize caching mechanisms for data that does not change frequently. This step minimizes repeated database queries.

Security Best Practices

  • Access Control:
    Ensure that the controller routes are protected with appropriate authorization levels (e.g., auth="user").
  • Input Validation:
    Actively validate and sanitize all user inputs both on the client side (using JavaScript) and the server side (using Odoo’s ORM).

Resource Optimization

  • Load Assets Efficiently:
    Use minified CSS and JavaScript files in production. This approach reduces the page load time and enhances user experience.
  • Monitor Performance:
    Leverage Odoo logs and server monitoring tools to actively debug performance issues. This ensures that your portal operates optimally even under high user loads.

Adopting these performance and security best practices helps create a robust Odoo website portal form view that users can rely on.


Additional Use Cases and Real-World Applications

The techniques outlined in this tutorial are not limited solely to student registration. You can apply these strategies to various other Odoo development scenarios. For instance:

Employee Onboarding Forms

Organizations can build similar form views for onboarding employees, capturing all necessary information and dynamically populating departments, roles, and office locations.

Customer Feedback Portals

Retail and service businesses can develop feedback portals where customers can register feedback, rate services, and interact with customer support. The same principles of dynamic data retrieval and form validation apply.

E-commerce Product Registrations

E-commerce websites can leverage the same form view structure to let users register products for warranty purposes or receive maintenance services.

By easily adapting the code structure, you actively reuse the concepts of an Odoo portal form view across various domains. This versatility demonstrates the strength and flexibility of the Odoo framework.


Managing Code Versions and Collaborating with Developers

As you enhance and extend your form view, managing code versions becomes critical. Using version control systems like Git allows you to track changes and collaborate with team members. Here are a few useful tips:

1. Setting Up Git

  • Initialize a Git Repository:
    Start by running git init in your module’s directory.
  • Create Branches for Features:
    Actively create feature branches for new enhancements. This practice keeps your main branch stable.

2. Code Reviews and Pull Requests

Engage your team with regular code reviews. Active collaboration helps identify potential issues and fosters a better understanding of the codebase.

3. Continuous Integration and Testing

Implement automated testing to actively validate new changes. Tools like Odoo’s test framework ensure that every update passes the necessary checks before merging.

By adopting these practices, you manage your module’s lifecycle in an efficient manner and maintain a high-quality Odoo portal form view.


Conclusion and Next Steps

In this tutorial, we actively demonstrated how to build and extend an Odoo portal form view for a student registration form. You learned how to integrate Python controllers, XML templates for breadcrumbs and form layouts, and even enhance user experience with JavaScript validation and CSS styling.

We began by outlining the fundamentals of Odoo website portal development and moved step-by-step through the creation of the controller and view files. Each section provided clear instructions and active transitions to guide you through the process. Moreover, we actively discussed methods to extend the functionality of your form view, such as multi-step registration and Ajax integration, while highlighting best practices for performance, security, and collaboration.

As you move forward, consider exploring further enhancements such as integrating payment gateways, adding more dynamic fields, or even connecting your form view with external APIs for richer functionality. Continue reading advanced topics in the Odoo Developer Documentation to build even more robust applications.

We hope you found this tutorial helpful and that you now have the skills to create your own custom Odoo portal form view. Please leave any comments or questions below, and join our community for more tips and updates on Odoo web development. Happy coding and see you in the next tutorial session!


Appendix: All Source Code Listings

For your convenience, here is the consolidated source code that we discussed throughout this article.

Python Controller Code

from odoo import http
from odoo.http import request

class WeblearnsPortal(http.Controller):

    @http.route(["/new/student"], type="http", auth="user", website=True)
    def registerStudentProfile(self, **kw):
        school_list = request.env['school.profile'].search([])
        return request.render("wb_portal.new_student_form_view_portal", {
            'schools': school_list,
            'page_name': "register_student"
        })

    @http.route(["/student/step1"], type="http", auth="user", website=True)
    def studentStepOne(self, **kw):
        school_list = request.env['school.profile'].search([])
        return request.render("wb_portal.student_step_one", {
            'schools': school_list,
            'page_name': "register_student_step1"
        })

    @http.route(["/student/step2"], type="http", auth="user", website=True, methods=['POST'])
    def studentStepTwo(self, **kw):
        return request.render("wb_portal.student_step_two", {
            'page_name': "register_student_step2"
        })

Breadcrumbs XML Template

<template id="portal_breadcrumbs" inherit_id="portal.portal_breadcrumbs">
    <xpath expr="//ol[hasclass('o_portal_submenu')]" position="inside">
        <li t-if="page_name == 'students_list_view'" class="breadcrumb-item">Students</li>
        <li t-if="page_name == 'register_student'" class="breadcrumb-item">Register Student</li>
        <li t-if="page_name == 'students_form_view'" class="breadcrumb-item">
            <a href="/my/students">Students</a> /
            <span t-out="student.name" />
        </li>
    </xpath>
</template>

Student Registration Form XML Template

<template id="new_student_form_view_portal">
    <t t-call="portal.portal_layout">
        <t t-call="portal.portal_table">
            <form>
                <div class="form-group row">
                    <label class="col-sm-2 col-form-label" for="name">Name</label>
                    <div class="col-sm-10">
                        <input type="char" name="name" id="name" class="form-control" placeholder="Enter Student Name"/>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="col-sm-2 col-form-label" for="school">School</label>
                    <div class="col-sm-10">
                        <select name="school" id="school" class="form-control">
                            <option>Selection School</option>
                            <t t-foreach="schools" t-as="school">
                                <option t-att-value="school.id">
                                    <t t-out="school.name" />
                                </option>
                            </t>
                        </select>
                    </div>
                </div>
                <div class="form-group row">
                    <div class="col-sm-10">
                        <button type="submit" class="btn btn-primary">Create Student Profile</button>
                    </div>
                </div>
            </form>
        </t>
    </t>
</template>

JavaScript Validation Code

<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.querySelector('form');
        form.addEventListener('submit', function (e) {
            const nameField = document.getElementById('name');
            const emailField = document.getElementById('email');
            if (!nameField.value || (emailField && !emailField.value)) {
                alert('Please fill in all required fields.');
                e.preventDefault();
            }
        });
    });
</script>

Custom CSS for Form Enhancements

/* custom_portal_styles.css */
.form-group label {
    font-weight: bold;
    color: #333;
}
.form-control {
    border-radius: 0.25rem;
    border: 1px solid #ccc;
}
.btn-primary {
    background-color: #007bff;
    border-color: #007bff;
}

By following this tutorial and examining each part of the code in detail, you now have all the necessary tools to build and enhance an effective Odoo portal form view. happy coding!


Discover more from teguhteja.id

Subscribe to get the latest posts sent to your email.

Leave a Reply

WP Twitter Auto Publish Powered By : XYZScripts.com